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.
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.