Constructors
When you create an object from a class, Python automatically runs a special method called the constructor. Its job is to set up the object’s starting values.
__init__
In Python, the constructor is always named __init__. It runs the moment you create a new object.
Here’s a UserAccount class. When someone signs up, you collect their username and email. But some values — like their login count or whether they’ve been verified — the app sets on its own:
class UserAccount:
def __init__(self, username, email):
# Values you pass in
self.username = username
self.email = email
# Values the app sets automatically
self.login_count = 0
self.is_verified = FalseThe parameters username and email come from whoever creates the object. login_count and is_verified always start the same way for every new account, so the constructor sets them itself.
self.username = username stores the value on the object. Without that line, username only exists inside __init__ and disappears when the constructor finishes. The self. prefix is what makes it stick to the object so you can access it later.
When you write UserAccount("maya", "[email protected]"), Python calls __init__ automatically. You never call it yourself.
Understanding self
self refers to the specific object being created. When Python runs __init__, it passes the new object in as self so the method knows which account it’s setting up.
maya = UserAccount("maya", "[email protected]")
jordan = UserAccount("jordan", "[email protected]")When maya is created, inside the class: self is maya.
When jordan is created, self is jordan.
That’s how each object ends up with its own username and email — self.username and self.email are stored on that specific instance.
You don’t pass self yourself — Python handles it automatically.
Accessing Attributes
Once an object is created, use dot notation to read its attributes:
maya = UserAccount("maya", "[email protected]")
print(maya.username) # maya
print(maya.email) # [email protected]
print(maya.is_verified) # FalseThe pattern is object.attribute_name — no parentheses, since you’re reading a value, not calling a method.