Private attributes in Python - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
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?"
Practice
__) in a Python class?Solution
Step 1: Understand private attribute naming
Private attributes start with double underscores to hide them from outside access.Step 2: Purpose of hiding attributes
This protects the data inside the object from accidental or unauthorized changes.Final Answer:
To hide the attribute from outside the class and protect it -> Option BQuick Check:
Private attributes = data protection [OK]
- Thinking private means accessible everywhere
- Confusing private with global variables
- Believing private speeds up code
age in a Python class?Solution
Step 1: Identify private attribute syntax
Private attributes start with exactly two underscores, like__age.Step 2: Check options
self.__age usesself.__age, which is correct. self.age is public, self._age is protected (single underscore), self.___age has three underscores which is invalid.Final Answer:
self.__age -> Option DQuick Check:
Private attribute = double underscore [OK]
- Using single underscore instead of double
- Adding too many underscores
- Forgetting underscores
class Person:
def __init__(self, name):
self.__name = name
def get_name(self):
return self.__name
p = Person('Anna')
print(p.get_name())
print(p.__name)Solution
Step 1: Understand private attribute access
The attribute__nameis private and cannot be accessed directly outside the class.Step 2: Check print statements
Callingp.get_name()returns 'Anna' correctly. Butp.__namecauses AttributeError because it's private.Final Answer:
Anna\nAttributeError -> Option CQuick Check:
Private attribute direct access = AttributeError [OK]
- Expecting direct access to private attribute
- Ignoring AttributeError on private access
- Confusing method call with attribute access
class Car:
def __init__(self, model):
self.__model = model
c = Car('Tesla')
print(c.__model)Solution
Step 1: Identify the error
Accessingc.__modeloutside the class causes AttributeError because__modelis private.Step 2: Fix by adding a getter method
Adding a method inside the class to returnself.__modelallows safe access.Final Answer:
Add a method inside class to return __model -> Option AQuick Check:
Private attribute access needs class method [OK]
- Trying to access private attribute directly
- Removing underscores breaks privacy
- Ignoring need for getter method
__balance in a BankAccount class and allow safe updating only through a method that adds money. Which code snippet correctly implements this?Solution
Step 1: Check private attribute usage
class BankAccount: def __init__(self): self.__balance = 0 def add_money(self, amount): self.__balance += amount def get_balance(self): return self.__balance usesself.__balanceconsistently and privately.Step 2: Verify method updates and access
Theadd_moneymethod safely updates__balance, andget_balancereturns it correctly.Final Answer:
The code using self.__balance consistently in all methods -> Option AQuick Check:
Private attribute updated only inside class methods [OK]
- Updating private attribute outside class
- Mixing private and public attribute names
- Not providing method to access private data
