Class definition syntax in Python - Time & Space Complexity
When we write a class in Python, it's important to know how the time it takes to run grows as we create more objects or call methods.
We want to see how the class setup affects the work done when using it.
Analyze the time complexity of the following code snippet.
class Counter:
def __init__(self, start=0):
self.count = start
def increment(self):
self.count += 1
def get_count(self):
return self.count
This code defines a simple class that keeps a count, can increase it by one, and return the current count.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The increment method adds 1 to the count each time it is called.
- How many times: Each call to increment does one simple addition operation.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: Each time you call increment, the work grows by one simple step, so it grows directly with how many times you call it.
Time Complexity: O(1)
This means each method call takes the same small amount of time, no matter how many times you use the class.
[X] Wrong: "Creating a class makes the program slower as it grows because it has to do a lot of work upfront."
[OK] Correct: Defining a class itself does not repeat work; only calling methods does work, and each call here is very quick.
Understanding how simple class methods run helps you explain how your code behaves when asked about efficiency in interviews.
"What if the increment method added a loop that counted up to the current count? How would the time complexity change?"