0
0
Pythonprogramming~5 mins

Name mangling in Python - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Name mangling
O(1)
Understanding Time Complexity

Let's explore how the time it takes to run code changes when using name mangling in Python.

We want to see how the program's steps grow as the input or usage grows.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

class MyClass:
    def __init__(self, value):
        self.__hidden = value

    def get_hidden(self):
        return self.__hidden

obj = MyClass(10)
print(obj.get_hidden())

This code uses name mangling to hide a variable inside a class and then accesses it through a method.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Accessing the mangled variable inside the method.
  • How many times: Once per method call; no loops or recursion here.
How Execution Grows With Input

Since there are no loops or repeated steps, the time to access the mangled name stays about the same no matter what.

Input Size (n)Approx. Operations
10About 1 access
100About 1 access
1000About 1 access

Pattern observation: The time does not grow with input size; it stays constant.

Final Time Complexity

Time Complexity: O(1)

This means the time to access a mangled name is constant and does not depend on input size.

Common Mistake

[X] Wrong: "Name mangling makes accessing variables slower because of extra steps."

[OK] Correct: Name mangling just changes the variable name internally; accessing it is still a simple, direct operation.

Interview Connect

Understanding how name mangling works and its performance helps you explain how Python handles private variables clearly and confidently.

Self-Check

"What if the method accessed the mangled variable inside a loop running n times? How would the time complexity change?"