Default values in constructors in Python - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
When we use default values in constructors, we want to know how this choice affects the time it takes to create objects.
We ask: Does setting default values change how long the constructor runs as we create more objects?
Analyze the time complexity of the following code snippet.
class Box:
def __init__(self, length=1, width=1, height=1):
self.length = length
self.width = width
self.height = height
boxes = []
n = 10 # Example value for n
for i in range(n):
boxes.append(Box())
This code creates n Box objects using default values in the constructor.
- Primary operation: The loop that creates and adds Box objects to the list.
- How many times: The loop runs n times, once for each Box created.
Each new object takes a small, fixed amount of time to create because the constructor just sets three values.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 30 simple assignments |
| 100 | About 300 simple assignments |
| 1000 | About 3000 simple assignments |
Pattern observation: The total work grows directly with the number of objects created.
Time Complexity: O(n)
This means the time to create n objects grows in a straight line with n.
[X] Wrong: "Using default values makes the constructor run faster or slower depending on n."
[OK] Correct: The default values are set once per object and do not add extra loops or complex steps, so the time per object stays the same regardless of defaults.
Understanding how constructors work with default values helps you explain object creation clearly and shows you can think about how code scales.
"What if the constructor included a loop that ran based on one of the input values? How would the time complexity change?"
Practice
__init__ method)?Solution
Step 1: Understand default values in constructors
Default values let you set a value for a parameter if no argument is given when creating an object.Step 2: Identify the effect on object creation
This means you can create an object without giving all arguments, and the defaults fill in the missing ones.Final Answer:
To allow creating objects without providing all arguments -> Option CQuick Check:
Default values = optional arguments [OK]
- Thinking defaults speed up the constructor
- Believing defaults prevent object creation
- Assuming defaults force all arguments
age in a Python class constructor?Solution
Step 1: Recall Python syntax for default parameters
Default values are set by assigning a value in the parameter list, likeage=30.Step 2: Check each option
def __init__(self, age=30): uses correct syntax. def __init__(self, age): age=30 tries to assign inside the method header, which is invalid. def __init__(self, age): age == 30 uses comparison operator instead of assignment. def __init__(self, age:30): uses incorrect type hint syntax.Final Answer:
def __init__(self, age=30): -> Option DQuick Check:
Default parameter = param=value [OK]
- Assigning default inside the method body
- Using == instead of = for defaults
- Confusing type hints with default values
class Person:
def __init__(self, name, age=25):
self.name = name
self.age = age
p = Person('Alice')
print(p.name, p.age)Solution
Step 1: Analyze the constructor parameters
The constructor hasage=25as a default, so ifageis not given, it uses 25.Step 2: Check object creation and print
We createp = Person('Alice')withoutage, soageis 25. Printingp.nameandp.ageshows 'Alice 25'.Final Answer:
Alice 25 -> Option AQuick Check:
Missing argument uses default [OK]
- Expecting error when argument is missing
- Assuming default is None if not given
- Confusing default with zero or empty string
class Car:
def __init__(self, model='Sedan', year):
self.model = model
self.year = yearSolution
Step 1: Check parameter order in constructor
In Python, parameters with default values must come after parameters without defaults.Step 2: Identify the error in parameter order
Here,model='Sedan'is a default parameter beforeyearwhich has no default. This causes a syntax error.Final Answer:
Default parameter must come after non-default parameters -> Option BQuick Check:
Default params last in list [OK]
- Placing default parameters before required ones
- Thinking __init__ needs return
- Forgetting self parameter
Book where the author defaults to 'Unknown' and pages defaults to 100 if not provided. Which constructor is correct?Solution
Step 1: Check parameter defaults and order
Bothauthorandpageshave default values, so order is flexible. Options B and C have syntax errors.Step 2: Verify constructor body assigns attributes
def __init__(self, author='Unknown', pages=100): self.author = author; self.pages = pages correctly sets defaults and assignsself.authorandself.pagesinside the constructor body.Final Answer:
def __init__(self, author='Unknown', pages=100): self.author = author; self.pages = pages -> Option AQuick Check:
Defaults set in params, assign inside method [OK]
- Incorrect default assignment syntax
- Not assigning parameters to self
- Mixing default values and assignments
