0
0
Pythonprogramming~10 mins

Default values in constructors in Python - Step-by-Step Execution

Choose your learning style9 modes available
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.
Execution Sample
Python
class Car:
    def __init__(self, color='red', wheels=4):
        self.color = color
        self.wheels = wheels

car1 = Car()
car2 = Car('blue', 6)
Creates two Car objects, one with default values and one with given values.
Execution Table
StepActionParametersAttributes SetOutput
1Create car1No parameterscolor='red', wheels=4car1.color='red', car1.wheels=4
2Create car2color='blue', wheels=6color='blue', wheels=6car2.color='blue', car2.wheels=6
3End--Objects created with correct attributes
💡 All objects created; constructor used defaults when no arguments given.
Variable Tracker
VariableStartAfter car1After car2Final
car1.colorundefinedredredred
car1.wheelsundefined444
car2.colorundefinedundefinedblueblue
car2.wheelsundefinedundefined66
Key Moments - 2 Insights
Why does car1 get 'red' and 4 wheels without passing arguments?
Because the constructor has default values for color and wheels, used when no arguments are given (see execution_table step 1).
What happens if we pass only one argument to the constructor?
The first parameter gets the passed value, and the second uses its default. This is shown by how car2 overrides both, but if only one was passed, the other would stay default.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is car1.color after creation?
Aundefined
B'red'
C'blue'
DNone
💡 Hint
Check execution_table row 1 under Attributes Set for car1.
At which step does the constructor use given parameters instead of defaults?
AStep 2
BStep 1
CStep 3
DNever
💡 Hint
Look at execution_table rows 1 and 2 to see when parameters are passed.
If we create car3 = Car('green'), what will car3.wheels be?
Agreen
Bundefined
C4
DError
💡 Hint
Default values apply to parameters not passed, see concept_flow and variable_tracker.
Concept Snapshot
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
Full Transcript
This example shows how Python constructors can have default values. When creating car1 without arguments, the constructor uses 'red' for color and 4 for wheels. When creating car2 with 'blue' and 6, those values override defaults. Variables track these changes step-by-step. Beginners often wonder why defaults apply or what happens if some arguments are missing. The execution table clarifies these points by showing each step's parameters and attribute settings.