Concept Flow - Default values in constructors
Start object creation
Call constructor with args?
Use given
Set attributes
Object ready
When creating an object, the constructor uses given values or defaults if none are provided.
class Car: def __init__(self, color='red', wheels=4): self.color = color self.wheels = wheels car1 = Car() car2 = Car('blue', 6)
| Step | Action | Parameters | Attributes Set | Output |
|---|---|---|---|---|
| 1 | Create car1 | No parameters | color='red', wheels=4 | car1.color='red', car1.wheels=4 |
| 2 | Create car2 | color='blue', wheels=6 | color='blue', wheels=6 | car2.color='blue', car2.wheels=6 |
| 3 | End | - | - | Objects created with correct attributes |
| Variable | Start | After car1 | After car2 | Final |
|---|---|---|---|---|
| car1.color | undefined | red | red | red |
| car1.wheels | undefined | 4 | 4 | 4 |
| car2.color | undefined | undefined | blue | blue |
| car2.wheels | undefined | undefined | 6 | 6 |
class ClassName:
def __init__(self, param=default):
self.attr = param
- Constructor uses given args or defaults
- Missing args get default values
- Allows flexible object creation