In Python, @classmethod marks a method that receives the class itself as its first argument, conventionally named cls, instead of an instance (self). You can call it on the class, Date.from_string(...), or on an instance.
The classic use is an alternative constructor: a method that parses some input and returns cls(...). Because cls is whichever class the method was called on, subclasses automatically get instances of the subclass.
classmethod is a built-in type (a class) that you call like a function: each call creates a new classmethod object. Like every built-in, it lives in the builtins module and is always available without an import.
Syntax
Usually written as a decorator.
python
class MyClass:
@classmethod
def create(cls, data):
return cls(data)
Call
What it does
MyClass.create(x)
Called on the class.
obj.create(x)
Also works; cls is still the class.
SubClass.create(x)
cls is SubClass.
classmethod(func)
The non-decorator form.
Use a class method when the method needs the class (to construct objects or read class attributes) but not a particular instance.
Library declarations
python
classmethod(function, /)
# class classmethod: usually used as @classmethod
Parameters
Parameter
Description
function
Required. A function whose first parameter will receive the class.
Return Value
Return Value
Description
classmethod
A class method object to store in the class body.
Python Examples
Example 1 — Build Objects from a String
Add a from_string() constructor next to the normal __init__.