Classes and objects in Python - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
When we use classes and objects, we want to know how long it takes to create and use them as our program grows.
We ask: How does the time to run change when we make more objects or call methods many times?
Analyze the time complexity of the following code snippet.
class Counter:
def __init__(self, start=0):
self.count = start
def increment(self):
self.count += 1
n = 10 # Example value for n
counters = [Counter() for _ in range(n)]
for counter in counters:
counter.increment()
This code creates a list of n Counter objects and then calls the increment method on each one.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Creating n objects and calling increment n times.
- How many times: Each operation happens once per object, so n times.
As we increase n, the number of objects and method calls grows directly with n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 20 (10 creations + 10 increments) |
| 100 | About 200 (100 creations + 100 increments) |
| 1000 | About 2000 (1000 creations + 1000 increments) |
Pattern observation: The total work grows evenly as n grows; doubling n doubles the work.
Time Complexity: O(n)
This means the time to create and update all objects grows in a straight line with the number of objects.
[X] Wrong: "Creating many objects is instant and does not affect time."
[OK] Correct: Each object takes time to create and use, so more objects mean more total time.
Understanding how object creation and method calls scale helps you explain program speed clearly and confidently.
"What if the increment method had a loop inside that runs m times? How would the time complexity change?"
Practice
class in Python?Solution
Step 1: Understand what a class represents
A class is like a blueprint or template that defines how objects are created and what they can do.Step 2: Identify the role of a class
Classes organize code by grouping data and functions that belong together, allowing creation of many objects from the same blueprint.Final Answer:
To create a blueprint for objects -> Option CQuick Check:
Class = blueprint for objects [OK]
- Thinking classes run code immediately
- Confusing classes with simple variables
- Believing classes only store data
Car in Python?Solution
Step 1: Recall Python class syntax
In Python, classes are defined using the keywordclassfollowed by the class name and parentheses.Step 2: Check each option
class Car(): usesclass Car():which is correct syntax. Others use wrong keywords or formats.Final Answer:
class Car(): -> Option AQuick Check:
Class definition starts with 'class' keyword [OK]
- Using 'def' instead of 'class'
- Using 'function' keyword (not Python)
- Missing 'class' keyword
class Dog():
def __init__(self, name):
self.name = name
def bark(self):
return f"{self.name} says Woof!"
my_dog = Dog("Buddy")
print(my_dog.bark())Solution
Step 1: Understand the __init__ method
The__init__method sets thenameattribute to "Buddy" whenmy_dogis created.Step 2: Analyze the bark method call
Thebarkmethod returns a string using the dog's name, so it returns "Buddy says Woof!".Final Answer:
Buddy says Woof! -> Option BQuick Check:
Method uses self.name = Buddy [OK]
- Forgetting to pass 'self' in methods
- Confusing class name with object name
- Expecting method to print instead of return
class Person():
def __init__(self, name):
name = name
p = Person("Alice")
print(p.name)Solution
Step 1: Check attribute assignment in __init__
The code assignsname = name, which only changes the local variable, not the object's attribute.Step 2: Correct assignment to object attribute
It should beself.name = nameto store the value in the object for later access.Final Answer:
Should assign to self.name, not name -> Option DQuick Check:
Use self.attribute = value to save data [OK]
- Assigning to local variable instead of self.attribute
- Forgetting self in method parameters
- Trying to print undefined variables
BankAccount that stores an account holder's name and balance. It should have a method deposit(amount) that adds money to the balance only if the amount is positive. Which code correctly implements this?Solution
Step 1: Check __init__ method for attributes
class BankAccount(): def __init__(self, name, balance=0): self.name = name self.balance = balance def deposit(self, amount): if amount > 0: self.balance += amount correctly setsself.nameandself.balancewith a default balance of 0.Step 2: Verify deposit method logic
class BankAccount(): def __init__(self, name, balance=0): self.name = name self.balance = balance def deposit(self, amount): if amount > 0: self.balance += amount addsamounttoself.balanceonly ifamount > 0, which matches the requirement.Final Answer:
Correctly implements the class with proper attribute initialization and deposit validation -> Option AQuick Check:
Check attribute setup and positive amount condition [OK]
- Not using self.balance to store balance
- Adding amount without checking if positive
- Overwriting balance instead of adding
- Missing default balance initialization
