@classmethod decorator
The @classmethod decorator can be applied on any method of a class. This decorator will allow us to call that method using the class name instead of the object.
Example: @classmethod
class person: totalObjects=0 def __init__(self): person.totalObjects=person.totalObjects+1 @classmethod def showcount(cls): print("Total objects: ",cls.totalObjects)
In the above example, @classmethod is applied on the showcount()
method. The showcount()
method has one parameter cls
, which refers to the person class.
Now, we can call the showcount()
method using the class name, as shown below.
>>>p1=person()
>>>p2=person()
>>>person.showcount()
Total objects: 2
However, the same method can be called using an object also.
>>>p1.person()
>>>p1.showcount()
Total objects: 2