0
0
Pythonprogramming~5 mins

Getter and setter methods in Python - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Getter and setter methods
O(1)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

Getting or setting a value takes the same small amount of time no matter how many objects exist.

Input Size (n)Approx. Operations
101 simple step (per call)
1001 simple step (per call)
10001 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.

Final Time Complexity

Time Complexity: O(1)

This means each getter or setter runs in constant time, no matter how big your program or data is.

Common Mistake

[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.

Interview Connect

Understanding that simple getters and setters run quickly helps you explain how object data is accessed efficiently in real programs.

Self-Check

"What if the setter method also searched a list inside the object before setting the value? How would the time complexity change?"