The built-in classmethod
function, is a decorator function that allows a method to be bound to a class rather than an instance. It is used to define a method that can be invoked directly without necessarily creating an instance of the class. This allows you to access and modify class-specific attributes and perform operations that are relevant to the entire class.
Syntax:
@classmethod def func(cls, arguments): #body or def func(cls, arguments): #body TargetClass.some_method = classmethod(func)
copy
Instance methods are meant to be used by objects and not by the class itself. By convention, instance methods have self
as the first parameter, which refers to the instance calling the method while class methods have cls
as the first parameter.
As shown above, calling the method with the class itself raises an error. By decorating the method with the @classmethod decorator, it effectively becomes accessible from both the class and its objects/instances, as shown below.
more examples are shown below
class School: instances = 0 #keep count of how many instances are initialised def __init__(self): self.name = 'an instance' School.instances += 1 def countInstances(cls): return cls.instances School.count_instances = classmethod(countInstances) S1 = School() S2 = School() S3 = School() S4 = School() print(School.count_instances())
copy
Output:
4
We also have static methods ,which unlike class methods, have no access to the class state and cannot modify it. Static methods are defined using the builtin @staticmethod decorator/function.