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.
Jump into concepts and practice - no test required
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__init__ method)?age in a Python class constructor?age=30.class Person:
def __init__(self, name, age=25):
self.name = name
self.age = age
p = Person('Alice')
print(p.name, p.age)age=25 as a default, so if age is not given, it uses 25.p = Person('Alice') without age, so age is 25. Printing p.name and p.age shows 'Alice 25'.class Car:
def __init__(self, model='Sedan', year):
self.model = model
self.year = yearmodel='Sedan' is a default parameter before year which has no default. This causes a syntax error.Book where the author defaults to 'Unknown' and pages defaults to 100 if not provided. Which constructor is correct?author and pages have default values, so order is flexible. Options B and C have syntax errors.self.author and self.pages inside the constructor body.