Concept Flow - Purpose of constructors
Create object
Call constructor __init__
Initialize attributes
Object ready to use
When you create an object, Python automatically calls the constructor __init__ to set up initial values.
Jump into concepts and practice - no test required
class Dog: def __init__(self, name): self.name = name my_dog = Dog("Buddy") print(my_dog.name)
| Step | Action | Evaluation | Result |
|---|---|---|---|
| 1 | Create Dog object with name 'Buddy' | Call Dog.__init__(self, 'Buddy') | Object created |
| 2 | Constructor finishes | Object initialized | my_dog.name = 'Buddy' |
| 3 | Print my_dog.name | Access attribute | Output: Buddy |
| Variable | Start | After Step 1 | After Step 2 | Final |
|---|---|---|---|---|
| self.name | undefined | 'Buddy' | 'Buddy' | 'Buddy' |
| my_dog | undefined | object created | object initialized | object with name 'Buddy' |
Constructor (__init__) is a special method called automatically when an object is created. It initializes the object's attributes with starting values. You define __init__ inside a class with self and parameters. When you create an object, __init__ runs to set it up. This makes objects ready to use right after creation.
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
return f"{self.name} says Woof!"
my_dog = Dog("Buddy")
print(my_dog.bark())class Car:
def __init__(self, model):
model = model
my_car = Car("Tesla")
print(my_car.model)Book that stores title and author. Which constructor correctly initializes these attributes and allows creating a Book object with both values?