Last Updated on November 16, 2024 by sandeeppote
Class Methods are like Class Varaibles which works on Class but not on object level.
So this methods are bound to class and not object. See class varaibles here
Clas Methods are decorated with @classmethod attribute to the method in class.
This method can be called without creating instance of the class.
See below example definition and usage of class method.
In the above example get_instance_counter() method is decorated as @classmethod and a cls variable is passed. This holdsthe class reference for which the method is called.
The constructor works normal with __init__ method and updates calss variable counter increments the counter when an instance is created. This class variable accessed in the get_instance_counter() method.
You can also provision Python class to have multiple constructor with class method. See here – How to add multiple constructor to Python class?
0 Comments
3 Pingbacks