Class Methods
Class method
Normally, we call methods on class instances. Occasionally you may have use for a method which can be called on the class itself. In this case, you can use the @classmethod decorator.
When a class method is called on the class, the first implicit argument will be the class (rather than an instance of the class).
This may be used to provide alternate constructors:
import math
class Circle(object):
def __init__(self, radius):
self.radius = radius
@classmethod
def from_area(cls, area):
return cls(math.sqrt(area / math.pi))
Now we can create an instance of Circle by providing an area instead of a radius. Subclasses of Circle may also use this method and the correct subclass will be passed in as cls.
>>> circle = Circle.from_area(176.71458676442586)
>>> circle.radius
7.5
The dict class uses the classmethod decorator to provide the alternate constructor fromkeys. The datetime.datetime class also uses the classmethod decorator to provide the alternate constructors now, fromtimestamp, and fromordinal.