Public attributes in Python - Time & Space 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.
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 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.
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 |
|---|---|
| 10 | 10 attribute accesses or sets |
| 100 | 100 attribute accesses or sets |
| 1000 | 1000 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.
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.
[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.
Understanding that attribute access is fast and constant helps you write clear and efficient code, which is a valuable skill in programming and interviews.
"What if we changed the public attribute to a property with a method behind it? How would the time complexity change?"