Class-aware factory methods
Construct an object from an alternate representation while preserving the calling subclass.
Python · Decorator
@classmethod turns a method into one whose implicit first argument is the class. It may be called through a class or instance, and subclass calls receive the subclass.
Use @classmethod when a method should receive its class rather than an instance. Python supplies that class as the first argument, and calls through a subclass supply the subclass, enabling class-aware behavior and construction.
@classmethod
def method(cls, arg1, arg2): ...| Name | Type | Description |
|---|---|---|
cls | type | The class object supplied implicitly by Python; conventionally named cls. |
*args, **kwargs | object | Any explicitly declared arguments after cls. |
The decorated method's return value; the page does not specify a separate return type.
class User:
def __init__(self, name):
self.name = name
@classmethod
def guest(cls):
return cls("guest")
class Admin(User):
pass
user = Admin.guest()
assert type(user) is Admin
assert user.name == "guest"The decorator lets a factory method receive the class used for the call, so inherited class methods can construct the appropriate subclass.
Construct an object from an alternate representation while preserving the calling subclass.
Implement behavior that needs class-level context rather than a particular object.
@classmethod transforms a method so its first implicit argument is the class, conventionally named cls. It can be called on either the class or an instance.
Follow-up: What happens through inheritance? The class object for the derived class is passed when the method is called on that derived class.
A class method can be invoked as C.f() or C().f(). In the instance form, Python ignores the instance itself and uses its class for the implicit argument.
Follow-up: Can the method distinguish two instances? Not from the implicit argument alone, because the instance is not passed.
A class method receives the class as its implicit first argument, so it can implement behavior that depends on the calling class. This is useful for class-aware factories and inherited constructors.
Follow-up: Why is cls preferable to naming the base class directly? Because calls on derived classes receive the derived class object.
staticmethodpropertyFunction definitions