Static methods in Python are methods that belong to the class rather than an instance.
They don’t take self
(instance) or cls
(class) as their first parameter.
Static methods are commonly used for utility functions related to the class.
Example:
class Math:
@staticmethod
def add(a, b):
return a + b
result = Math.add(1, 2)
print(result) # Output: 3
Here, add()
works without creating an object of the Math class.
When to Use Static Methods
- When the method does not need instance or class data.
- For utility functions related to the class.
- To keep code organized and grouped logically under a class.
Best Practices
- Use
@staticmethod
when the method logically belongs to the class but doesn’t interact with its state. - Avoid using it for operations that rely on self or cls (use instance or class methods instead).
- Good for helper functions like math operations, validators, or formatters.
👉 Next tutorial: Python Instance vs Class Variables