Getter and setter methods in Python - Time & Space Complexity
We want to see how long getter and setter methods take to run as the program grows.
How does the time to get or set a value change when we use these methods?
Analyze the time complexity of the following code snippet.
class Person:
def __init__(self, name):
self._name = name
def get_name(self):
return self._name
def set_name(self, new_name):
self._name = new_name
This code defines a simple class with getter and setter methods to access and update a name.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Accessing or updating a single variable inside the object.
- How many times: Each getter or setter runs once per call, no loops or repeated steps inside.
Getting or setting a value takes the same small amount of time no matter how many objects exist.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 simple step (per call) |
| 100 | 1 simple step (per call) |
| 1000 | 1 simple step (per call) |
Pattern observation: The time grows directly with how many times you call the method, but each call is very fast and does not depend on data size.
Time Complexity: O(1)
This means each getter or setter runs in constant time, no matter how big your program or data is.
[X] Wrong: "Getter and setter methods take longer as the number of objects grows."
[OK] Correct: Each method only accesses or changes one value, so the time does not depend on how many objects exist.
Understanding that simple getters and setters run quickly helps you explain how object data is accessed efficiently in real programs.
"What if the setter method also searched a list inside the object before setting the value? How would the time complexity change?"