A class method is a method that’s shared among all objects. To call a class method, put the class as the first argument.
Class methods can be can be called from instances and from the class itself. All of these use the same method. The method can use the classes variables and methods.
Related course: Complete Python Bootcamp: Go from zero to hero in Python
To turn a method into a classmethod, add @classmethod before the method definition. As parameter the method always takes the class.
The example below defines a class method. The class method can then be used by the class itself. In this example the class method uses the class property name.
You can use a classmethod with both objects and the class:
apple = Fruit()
The parameter name now belongs to the class, if you’d change the name by using an object it ignores that. But if you’d do that by the class it changes, example below:
Often the pythonic notation is used, but this is not strictly required.
You can also use a classmethod like this:
Like a static method, a class method doesn’t need an object to be instantiated.
A class method differs from a static method in that a static method doesn’t know about the class itself. In a classmethod, the parameter is always the class itself.
a static method knows nothing about the class or instance. You can just as well use a function call.
a class method gets the class when the method is called. It knows abouts the classes attributes and methods.
Exercises for classmethod article:
- What is a classmethod?
- How does a classmethod differ from a staticmethod?
Download answers in exercise section.