What is the difference between `staticmethod` and `classmethod` in Python?
`staticmethod` does not receive the instance or class as the first argument, while `classmethod` receives the class. Use them for different purposes within a class.
In Python, both staticmethod
and classmethod
are decorators that define methods with different purposes within a class. A staticmethod
does not take an implicit first argument; it does not receive the instance (self
) or the class (cls
) as an argument. This means it behaves like a regular function, but it belongs to the class's namespace. It is useful for utility functions that don't require access to instance or class data:
class MathUtils:
@staticmethod
def add(x, y):
return x + y
In contrast, a classmethod
takes the class itself as the first argument. This allows it to access and modify class state, making it suitable for factory methods or methods that operate on the class as a whole:
class Person:
population = 0
@classmethod
def create(cls, name):
cls.population += 1
return cls(name)
By understanding the differences between these two decorators, you can better organize your class methods according to their functionality and intended use.