Creating objects in Python - Performance & Efficiency
Start learning this pattern below
Jump into concepts and practice - no test required
When we create objects in Python, it takes some time to set up each one.
We want to know how the time needed grows as we make more objects.
Analyze the time complexity of the following code snippet.
class Item:
def __init__(self, value):
self.value = value
items = []
n = 10 # Example value for n
for i in range(n):
items.append(Item(i))
This code creates a list of n objects, each holding a value.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Creating a new object inside the loop.
- How many times: Exactly
ntimes, once per loop cycle.
Each new object takes a little time, so total time grows as we add more.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 object creations |
| 100 | About 100 object creations |
| 1000 | About 1000 object creations |
Pattern observation: The time grows directly with the number of objects created.
Time Complexity: O(n)
This means if you double the number of objects, the time to create them roughly doubles too.
[X] Wrong: "Creating many objects happens instantly, so time doesn't grow with more objects."
[OK] Correct: Each object needs some setup time, so more objects mean more total time.
Understanding how object creation time grows helps you write efficient code and explain your choices clearly.
"What if we created objects inside a nested loop instead? How would the time complexity change?"
Practice
__init__ method in a Python class?Solution
Step 1: Understand the role of
The__init____init__method is called automatically when a new object is created from a class.Step 2: Identify what
It sets up the initial state by assigning values to the object's attributes.__init__doesFinal Answer:
To initialize the object's attributes when it is created -> Option CQuick Check:
__init__initializes object attributes [OK]
__init__ sets up new objects [OK]- Thinking
__init__deletes objects - Confusing
__init__with printing methods - Believing
__init__defines new classes
Car in Python?Solution
Step 1: Recall Python object creation syntax
In Python, you create an object by calling the class name followed by parentheses.Step 2: Eliminate invalid syntaxes
new Car()is Java/C++ style, invalid in Python.Car.create()assumes a non-existent method.Car[]is invalid. OnlyCar()works.Final Answer:
car = Car() -> Option BQuick Check:
UseClassName()to create objects [OK]
- Using 'new' keyword like other languages
- Trying to call a non-existent create() method
- Using square brackets instead of parentheses
class Dog:
def __init__(self, name):
self.name = name
d = Dog('Buddy')
print(d.name)Solution
Step 1: Understand object creation and attribute assignment
TheDogclass has an__init__method that setsself.nameto the given argument.Step 2: Trace the code execution
Whend = Dog('Buddy')runs,d.namebecomes 'Buddy'. Printingd.nameoutputs 'Buddy'.Final Answer:
Buddy -> Option AQuick Check:
Object attribute prints assigned value [OK]
- Printing class name instead of attribute
- Expecting 'name' string output
- Confusing attribute with variable name
class Person:
def __init__(self, age):
age = age
p = Person(30)
print(p.age)Solution
Step 1: Check attribute assignment inside
The code assigns__init__age = age, which only changes the local variable, not the object's attribute.Step 2: Correct way to assign attribute
It should beself.age = ageto store the value in the object.Final Answer:
Attribute not assigned to self -> Option AQuick Check:
Useself.attribute = valueto store data [OK]
- Forgetting to use self for attributes
- Confusing local variables with object attributes
- Assuming assignment without self works
Book that stores title and author. Which code correctly creates an object and prints the title and author?Solution
Step 1: Check attribute assignment in constructor
The correct code defines__init__withtitleandauthorparameters and assignsself.title = titleandself.author = author.Step 2: Verify object creation and printing
The object is created by passing argumentsBook('1984', 'Orwell')matching the parameters, and both attributes print correctly. Others fail on missingself, incomplete assignments, or parameter mismatch.Final Answer:
Correctly assigns both attributes to self using parameters -> Option DQuick Check:
Assign all attributes with self and pass parameters [OK]
- Not assigning attributes to self
- Missing parameters in constructor
- Providing arguments to a parameterless constructor
