0
0
Pythonprogramming~5 mins

Private attributes in Python - Time & Space Complexity

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

Scenario Under Consideration

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.

Identify Repeating Operations
  • Primary operation: Calling the method to get the private attribute.
  • How many times: 1000 times in the loop.
How Execution Grows With Input

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
1010 method calls
100100 method calls
10001000 method calls

Pattern observation: The work grows directly with the number of times we access the private attribute.

Final Time Complexity

Time Complexity: O(n)

This means if you access the private attribute twice as many times, the program takes about twice as long.

Common Mistake

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

Interview Connect

Understanding how attribute access scales helps you write clear and efficient code, which is a useful skill in many programming tasks.

Self-Check

"What if we replaced the method call with direct access to the attribute? How would the time complexity change?"