Use cases for each method type in Python - Time & Space Complexity
When we use different types of methods in Python classes, their time cost can vary depending on how they access data.
We want to see how the choice of method type affects how long the program takes as input grows.
Analyze the time complexity of these method types in a class.
class Example:
class_var = [i for i in range(1000)]
def instance_method(self, n):
return sum(self.class_var[:n])
@classmethod
def class_method(cls, n):
return sum(cls.class_var[:n])
@staticmethod
def static_method(n):
return sum(range(n))
This code shows three method types accessing data differently and summing numbers up to n.
Look at what repeats when each method runs.
- Primary operation: Summing numbers in a list or range.
- How many times: The sum runs over n items each call.
As n grows, the sum operation takes longer because it adds more numbers.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The work grows directly with n, so doubling n doubles the work.
Time Complexity: O(n)
This means the time to run these methods grows in a straight line with the input size n.
[X] Wrong: "Static methods are always faster because they don't use class or instance data."
[OK] Correct: Static methods can still do work proportional to input size, like summing n numbers, so their time depends on what they do, not just method type.
Understanding how method types affect time helps you explain your code choices clearly and shows you know how data access impacts performance.
What if the instance method accessed a large nested list instead of a simple list? How would that change the time complexity?