Class attributes in Python - Time & Space Complexity
Let's see how the time it takes to run code with class attributes changes as we create more objects.
We want to know how the program's work grows when using class attributes in multiple instances.
Analyze the time complexity of the following code snippet.
class Dog:
legs = 4 # class attribute
def __init__(self, name):
self.name = name # instance attribute
def bark(self):
return f"{self.name} says woof!"
# Creating multiple Dog objects
n = 10 # example value for n
dogs = [Dog(f"Dog{i}") for i in range(n)]
This code defines a class with a shared class attribute and creates a list of dog objects.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Creating
nDog objects in a loop. - How many times: The loop runs
ntimes, once for each dog.
Each new dog object takes a small, fixed amount of work to create.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 object creations |
| 100 | About 100 object creations |
| 1000 | About 1000 object creations |
Pattern observation: The work grows directly with the number of objects created.
Time Complexity: O(n)
This means the time to create all dog objects grows in a straight line as you add more dogs.
[X] Wrong: "Accessing a class attribute inside each object makes the program slower as more objects are created."
[OK] Correct: Class attributes are shared and stored once, so accessing them does not add extra work per object beyond creating the object itself.
Understanding how class attributes affect performance helps you write clear and efficient object-oriented code, a useful skill in many programming tasks.
"What if we added a loop inside the bark method that runs m times? How would the time complexity change when creating and using n dogs?"