__init__ method behavior in Python - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
Let's explore how the time it takes to run the __init__ method changes as we create more objects.
We want to know how the work grows when making many instances of a class.
Analyze the time complexity of the following code snippet.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
people = []
n = 10
for i in range(n):
people.append(Person(f"Person{i}", i))
This code creates n Person objects, each with a name and age, and stores them in a list.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Creating a Person object by running
__init__once per loop. - How many times: Exactly
ntimes, once for each object created.
Each new object requires running __init__ once, so the total work grows directly with the number of objects.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 initializations |
| 100 | 100 initializations |
| 1000 | 1000 initializations |
Pattern observation: The work grows in a straight line as we add more objects.
Time Complexity: O(n)
This means the time to create all objects grows directly with how many objects we make.
[X] Wrong: "The __init__ method runs only once no matter how many objects are created."
[OK] Correct: Each object needs its own setup, so __init__ runs every time we make a new object.
Understanding how object creation time grows helps you explain how programs handle many items efficiently.
"What if the __init__ method included a loop that runs m times inside it? How would the time complexity change?"
Practice
What is the main purpose of the __init__ method in a Python class?
Solution
Step 1: Understand the role of
The__init____init__method runs automatically when an object is created to set up initial values.Step 2: Compare options with this role
Only To set up initial values for the object's attributes describes setting initial attribute values, which matches__init__'s purpose.Final Answer:
To set up initial values for the object's attributes -> Option DQuick Check:
__init__sets initial values = A [OK]
__init__ sets starting info for objects [OK]- Thinking
__init__deletes objects - Confusing
__init__with printing methods - Believing
__init__creates classes
Which of the following is the correct way to define an __init__ method inside a Python class?
class Car:
?Solution
Step 1: Check method name and parameters
The method must be named exactly__init__and includeselfas the first parameter.Step 2: Compare options
Only def __init__(self, model): uses the correct name and includesselfproperly.Final Answer:
def __init__(self, model): -> Option AQuick Check:
Correct__init__syntax = D [OK]
self as first parameter in __init__ [OK]- Omitting
selfparameter - Misspelling
__init__method name - Using wrong method names like
initor__start__
What will be the output of this code?
class Dog:
def __init__(self, name):
self.name = name
my_dog = Dog("Buddy")
print(my_dog.name)Solution
Step 1: Understand object creation and attribute assignment
The__init__method setsself.nameto "Buddy" whenmy_dogis created.Step 2: Check the print statement
Printingmy_dog.nameoutputs the string "Buddy" stored in the attribute.Final Answer:
Buddy -> Option AQuick Check:
Object attribute value = Buddy [OK]
__init__ [OK]- Printing class name instead of attribute
- Expecting attribute name instead of value
- Assuming code causes error
Find the error in this class definition:
class Person:
def __init__(name):
self.name = name
p = Person("Alice")Solution
Step 1: Check
The__init__method parameters__init__method must haveselfas the first parameter, but it is missing here.Step 2: Identify impact of missing
Withoutselfself,self.namecauses an error becauseselfis undefined.Final Answer:
Missingselfparameter in__init__-> Option BQuick Check:
__init__needsselffirst [OK]
self as first __init__ parameter [OK]- Forgetting
selfin method parameters - Thinking class name must change
- Missing parentheses when creating object
Consider this class:
class Book:
def __init__(self, title, author="Unknown"):
self.title = title
self.author = author
b1 = Book("Python 101")
b2 = Book("Learn AI", "Dr. Smith")
print(b1.author, b2.author)What will be printed?
Solution
Step 1: Understand default parameter in
The__init__authorparameter has a default value "Unknown", so it is optional when creating an object.Step 2: Analyze object creations
b1is created with only title, soauthoris "Unknown".b2provides both title and author "Dr. Smith".Step 3: Check print output
Printingb1.authorandb2.authorprints "Unknown Dr. Smith".Final Answer:
Unknown Dr. Smith -> Option CQuick Check:
Default parameters fill missing values = A [OK]
__init__ [OK]- Expecting error when argument is missing
- Mixing up title and author values
- Assuming both arguments are always required
