Private attributes in Python - Time & Space Complexity
Let's see how using private attributes affects the speed of a program.
We want to know how the time to access or change private attributes grows as the program runs.
Analyze the time complexity of the following code snippet.
class MyClass:
def __init__(self, value):
self.__private = value
def get_private(self):
return self.__private
obj = MyClass(10)
for i in range(1000):
x = obj.get_private()
This code creates an object with a private attribute and accesses it 1000 times in a loop.
- Primary operation: Calling the method to get the private attribute.
- How many times: 1000 times in the loop.
Each time we increase the number of times we access the private attribute, the total work grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 method calls |
| 100 | 100 method calls |
| 1000 | 1000 method calls |
Pattern observation: The work grows directly with the number of times we access the private attribute.
Time Complexity: O(n)
This means if you access the private attribute twice as many times, the program takes about twice as long.
[X] Wrong: "Accessing private attributes is slower because of the double underscore."
[OK] Correct: The double underscore only changes the attribute name internally; accessing it through a method is just a simple operation repeated many times.
Understanding how attribute access scales helps you write clear and efficient code, which is a useful skill in many programming tasks.
"What if we replaced the method call with direct access to the attribute? How would the time complexity change?"