Name mangling in Python - Time & Space 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.
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 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.
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 |
|---|---|
| 10 | About 1 access |
| 100 | About 1 access |
| 1000 | About 1 access |
Pattern observation: The time does not grow with input size; it stays constant.
Time Complexity: O(1)
This means the time to access a mangled name is constant and does not depend on input size.
[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.
Understanding how name mangling works and its performance helps you explain how Python handles private variables clearly and confidently.
"What if the method accessed the mangled variable inside a loop running n times? How would the time complexity change?"