Python Reference ยท Built-in Functions
Python classmethod() decorator
Reference for Python classmethod: define methods that receive the class as cls, build alternative constructors, work with inheritance and compare with staticmethod.
classmethod is a built-in decorator that turns a function defined in a class body into a class method. A class method receives the class itself as its first argument, conventionally named cls, instead of an instance. You can call it on the class or on any instance.
The classic use is an alternative constructor: a named way to build an object from different input, such as a string or a dictionary. Because it uses cls, subclasses get instances of themselves automatically.
class Temperature: @classmethod def from_fahrenheit(cls, f): return cls((f - 32) * 5 / 9)
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
class C: @classmethod def method(cls, arg1, arg2): ...
| Name | Description |
|---|---|
function |
The function to wrap; its first parameter receives the class. |
Return value: a class-method descriptor. When accessed through a class or instance it produces a bound method whose first argument is the class (for an instance, type(instance)).
Raises: nothing at definition. Calling with wrong arguments raises TypeError as usual.
Usage notes
- Use
cls, not the class name.return cls(...)keeps subclasses working;return Point(...)always builds aPoint. - Alternative constructors are the main use:
from_string,from_dict,from_file,today. Name themfrom_xso the call site reads clearly. - Class state. A class method can read and change class attributes like
cls.count. Assigningcls.count += 1in a subclass creates a separate attribute on that subclass, which can surprise you. - Versus
staticmethod. A static method receives no automatic first argument and cannot see the class. Use a class method when you needcls, a static method when you do not. - Versus a normal method. An instance method needs an object first; a class method works with no instance at all.
- Called on an instance still passes the class, not the instance.
- Chaining with
property. Wrappingclassmethodaroundpropertywas allowed in Python 3.9 to 3.12, deprecated, and removed in 3.13. Use a custom descriptor or a metaclass property instead. - Abstract. Combine with
abc.abstractmethod(put@classmethodon top) to require subclasses to supply a constructor.
Related
staticmethod(),property(),super(),type()- Lessons: Methods, Classes, Inheritance