Class method#
A class method is a method that takes the class itself as its first argument (typically named cls
). It should be defined using the classmethod
decorator. A crucial feature of a class method is that it can be called not only from an instance of the class (like a typical method) but also directly from the class itself.
Inheritance#
The question is: does cls
refer to the ancestor (the class where the method is defined) or the descendant (the class from which the method is called)? In Python, cls
always refers to the descendant—the class on which the method is invoked—regardless of whether the method is inherited or overridden.
The following example defines the Base
class, which has a class method that allows us to identify the class we are operating on.
class Base:
@classmethod
def example_method(cls):
return cls
The following code is really obvious, as we call exmpale_method
from Desc1
itself, which was passed to the cls
argument.
class Desc1(Base):
pass
Desc1.example_method()
__main__.Desc1
More specific case refers to calling example_method
from super
.
class Desc2(Base):
@classmethod
def example_method(cls):
return super().example_method()
Desc2.example_method()
__main__.Desc2
But the result is the same - cls
still refers to the class from which the method was called.