Skip to content

Classes and Objects

A class is a blueprint for creating objects β€” it bundles data (attributes) and behavior (methods) together. An object (or instance) is a concrete thing built from that blueprint. __init__ is the constructor, called automatically when you create a new instance, and self refers to the specific instance a method is operating on.

class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breed
def bark(self):
return f"{self.name} says Woof!"
fido = Dog("Fido", "Labrador")
print(fido.bark()) # Fido says Woof!
print(fido.name) # Fido
class Counter:
def __init__(self):
self.count = 0
def increment(self):
self.count += 1
c = Counter()
c.increment()
c.increment()
print(c.count) # 2

Forgetting self as the first parameter of an instance method, or forgetting to prefix attribute access with self. inside the class β€” both cause NameError or TypeError.

class Broken:
def __init__(name): # missing self -- 'name' silently becomes self
name = name # this is a local variable, not an attribute!
# Fixed:
class Fixed:
def __init__(self, name):
self.name = name # self.name is the actual instance attribute
  1. What does self represent inside a method?

    AnswerThe specific instance the method is being called on β€” Python passes it automatically as the first argument.
  2. What is __init__ called for?

    AnswerIt's the constructor β€” Python calls it automatically right after a new instance is created, to set up initial attribute values.
  3. What happens if you assign name = name inside __init__ instead of self.name = name?

    AnswerIt creates/reassigns a local variable that disappears when the method returns β€” the instance never gets a name attribute.