Object initialization flow in Python - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
When we create objects in Python, some steps happen behind the scenes. Understanding how long these steps take helps us write faster programs.
We want to know how the time to set up an object changes as we add more data or features.
Analyze the time complexity of the following code snippet.
class Person:
def __init__(self, name, hobbies):
self.name = name
self.hobbies = []
for hobby in hobbies:
self.hobbies.append(hobby)
p = Person("Alice", ["reading", "swimming", "coding"])
This code creates a Person object and copies a list of hobbies into a new list inside the object.
- Primary operation: The for-loop that goes through each hobby in the input list.
- How many times: Once for each hobby in the hobbies list.
As the number of hobbies grows, the time to copy them grows too, because each hobby is added one by one.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 steps to copy hobbies |
| 100 | About 100 steps to copy hobbies |
| 1000 | About 1000 steps to copy hobbies |
Pattern observation: The time grows directly with the number of hobbies. Double the hobbies, double the time.
Time Complexity: O(n)
This means the time to set up the object grows in a straight line with the number of hobbies you give it.
[X] Wrong: "Initializing an object always takes the same time, no matter how much data it has."
[OK] Correct: If the object copies or processes a list or other data, it takes longer when there is more data to handle.
Understanding how object setup time grows helps you explain your code choices clearly and shows you know how programs handle data behind the scenes.
"What if we changed the hobbies list to a set instead of a list? How would the time complexity change?"
Practice
__init__ method in a Python class?Solution
Step 1: Understand the role of
The__init____init__method runs automatically when a new object is created from a class.Step 2: Identify what
It sets up the initial state of the object by assigning values to its attributes.__init__doesFinal Answer:
To initialize a new object when it is created -> Option CQuick Check:
__init__initializes objects [OK]
- Confusing __init__ with __del__
- Thinking __init__ is for printing
- Believing __init__ defines class variables
__init__ method that takes a parameter name in a Python class?Solution
Step 1: Recall
The first parameter must be__init__method signatureselfto refer to the new object.Step 2: Check parameter list
To accept anameargument, it must be added afterself.Final Answer:
def __init__(self, name): -> Option AQuick Check:
First param is self, then others [OK]
- Omitting self parameter
- Using init instead of __init__
- Missing parameters after self
class Car:
def __init__(self, brand):
self.brand = brand
my_car = Car('Toyota')
print(my_car.brand)Solution
Step 1: Understand object creation
Creatingmy_car = Car('Toyota')calls__init__with 'Toyota' as brand.Step 2: Check attribute assignment and print
Thebrandattribute ofmy_caris set to 'Toyota', so printingmy_car.brandoutputs 'Toyota'.Final Answer:
Toyota -> Option BQuick Check:
Attribute value prints 'Toyota' [OK]
- Expecting class name instead of attribute value
- Confusing attribute name with value
- Thinking print causes error
class Person:
def __init__(self, age):
age = age
p = Person(30)
print(p.age)Solution
Step 1: Check attribute assignment inside __init__
The code assignsage = age, which only reassigns the local variable, not the object's attribute.Step 2: Understand how to assign attributes
To store the value in the object, it should beself.age = age.Final Answer:
The attribute age is not assigned to self -> Option AQuick Check:
Use self.attribute = value to save data [OK]
- Forgetting self in attribute assignment
- Thinking local variable sets object attribute
- Ignoring error messages about missing attributes
class Book:
def __init__(self, title, author='Unknown'):
self.title = title
self.author = author
b1 = Book('Python 101')
b2 = Book('Learn AI', 'Alice')What are the values of
b1.author and b2.author?Solution
Step 1: Understand default parameter usage
Theauthorparameter has a default value 'Unknown', used if no argument is given.Step 2: Check object creation
b1is created with onlytitle, soauthordefaults to 'Unknown'.b2provides 'Alice' explicitly.Final Answer:
b1.author is 'Unknown', b2.author is 'Alice' -> Option DQuick Check:
Default params fill missing arguments [OK]
- Assuming missing argument becomes None
- Mixing title and author values
- Forgetting default parameter behavior
