0
0
Pythonprogramming~5 mins

Public attributes in Python - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Public attributes
O(1)
Understanding Time Complexity

When working with public attributes in Python classes, it's helpful to understand how accessing or modifying these attributes affects the program's speed.

We want to know how the time to get or set a public attribute changes as the program runs.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

class Car:
    def __init__(self, color):
        self.color = color  # public attribute

car = Car('red')
print(car.color)
car.color = 'blue'
print(car.color)

This code creates a Car object with a public attribute color, then reads and changes it.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Accessing or setting the public attribute color.
  • How many times: Each access or assignment happens once here, but could happen many times in a bigger program.
How Execution Grows With Input

Accessing or changing a public attribute takes the same amount of time no matter how many objects or attributes exist.

Input Size (n)Approx. Operations
1010 attribute accesses or sets
100100 attribute accesses or sets
10001000 attribute accesses or sets

Pattern observation: Each attribute access or change takes the same time, so the total time grows directly with how many times you do it.

Final Time Complexity

Time Complexity: O(1)

This means accessing or changing a public attribute takes a constant amount of time, no matter how big your program or data is.

Common Mistake

[X] Wrong: "Accessing a public attribute gets slower if I have many objects or attributes."

[OK] Correct: Each attribute access looks up just one value and does not depend on how many objects or attributes exist elsewhere.

Interview Connect

Understanding that attribute access is fast and constant helps you write clear and efficient code, which is a valuable skill in programming and interviews.

Self-Check

"What if we changed the public attribute to a property with a method behind it? How would the time complexity change?"