September 2026
1051 pages
35h 4m
English
Besides the static methods that can exist separately from an instance, there is another kind of method that doesn’t refer to an instance of a class. These class methods expect a reference to the class for which they are called as the first parameter. To define a class method, you can use the built-in classmethod function.
In the following example, the three A, B, and C classes are defined, where C and B inherit from A, respectively. Class A has a class method m that outputs the type of the instance that was used to call the method:
class A: def m(cls): print("I am", cls) m = classmethod(m)class B(A): passclass C(A): passA.m()a = A()b = B()c = C()a.m()b.m()c.m()
The output of the program looks as follows:
I am <class '__main__.A'> ...
Read now
Unlock full access