0
0
Pythonprogramming~5 mins

Class attributes in Python - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Class attributes
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Creating n Dog objects in a loop.
  • How many times: The loop runs n times, once for each dog.
How Execution Grows With Input

Each new dog object takes a small, fixed amount of work to create.

Input Size (n)Approx. Operations
10About 10 object creations
100About 100 object creations
1000About 1000 object creations

Pattern observation: The work grows directly with the number of objects created.

Final Time Complexity

Time Complexity: O(n)

This means the time to create all dog objects grows in a straight line as you add more dogs.

Common Mistake

[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.

Interview Connect

Understanding how class attributes affect performance helps you write clear and efficient object-oriented code, a useful skill in many programming tasks.

Self-Check

"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?"