Protected attributes in Python - Time & Space Complexity
Let's see how using protected attributes affects the time it takes for a program to run.
We want to know how the program's steps grow when it accesses these special attributes many times.
Analyze the time complexity of the following code snippet.
class MyClass:
def __init__(self, values):
self._values = values # protected attribute
def sum_values(self):
total = 0
for val in self._values:
total += val
return total
obj = MyClass([1, 2, 3, 4, 5])
print(obj.sum_values())
This code defines a class with a protected list attribute and sums its values.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the list stored in the protected attribute.
- How many times: Once for each item in the list.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 additions |
| 100 | About 100 additions |
| 1000 | About 1000 additions |
Pattern observation: The number of steps grows directly with the number of items in the list.
Time Complexity: O(n)
This means the time to sum values grows in a straight line as the list gets bigger.
[X] Wrong: "Using a protected attribute makes the code slower because of the underscore."
[OK] Correct: The underscore is just a naming hint; it does not slow down the program or add extra steps.
Understanding how attribute access affects performance helps you write clear and efficient code, a skill valued in many coding challenges.
"What if the protected attribute held a dictionary instead of a list? How would the time complexity change when summing values?"