What is the difference between a function decorated with @staticmethod and one decorated with @classmethod?
Only the first argument differs:
In more detail...
When an object's method is called, it is automatically given an extra argument self
as its first argument. That is, method
def f(self, x, y)
must be called with 2 arguments. self
is automatically passed, and it is the object itself.
When the method is decorated
@classmethod
def f(cls, x, y)
the automatically provided argument is not self
, but the class of self
.
When the method is decorated
@staticmethod
def f(x, y)
the method is not given any automatic argument at all. It is only given the parameters that it is called with.
classmethod
is mostly used for alternative constructors.staticmethod
does not use the state of the object. It could be a function external to a class. It only put inside the class for grouping functions with similar functionality (for example, like Java's Math
class static methods)class Point
def __init__(self, x, y):
self.x = x
self.y = y
@classmethod
def frompolar(cls, radius, angle):
"""The `cls` argument is the `Point` class itself"""
return cls(radius * cos(angle), radius * sin(angle))
@staticmethod
def angle(x, y):
"""this could be outside the class, but we put it here
just because we think it is logically related to the class."""
return atan(y, x)
p1 = Point(3, 2)
p2 = Point.frompolar(3, pi/4)
angle = Point.angle(3, 2)