Python built-in Method - classmethod()

www‮.‬theitroad.com

The classmethod() method is a built-in function in Python that returns a class method for the given function. A class method is a method that is bound to the class and not the instance of the class. This means that it can be called on the class itself, rather than on an instance of the class.

Here is the syntax for classmethod() method:

classmethod(function)

where function is the function that will be turned into a class method.

Here is an example of how to use classmethod():

class MyClass:
    counter = 0
    
    def __init__(self):
        MyClass.counter += 1
        
    @classmethod
    def get_counter(cls):
        return cls.counter

obj1 = MyClass()
obj2 = MyClass()

print(obj1.get_counter())  # Output: 2
print(obj2.get_counter())  # Output: 2
print(MyClass.get_counter())  # Output: 2

In this example, MyClass has a class variable counter that keeps track of the number of instances of the class that have been created. counter is initialized to 0 when the class is defined.

The __init__() method is a constructor that is called each time a new instance of the class is created. It increments the counter class variable by 1 each time it is called.

The get_counter() method is a class method that returns the value of counter. It is decorated with @classmethod, which turns it into a class method.

get_counter() can be called either on an instance of the class (in which case the cls parameter will automatically be set to the class of the instance), or on the class itself (in which case cls will be set to the class).

In this example, get_counter() is called on both an instance of the class (obj1 and obj2) and on the class itself (MyClass). In each case, it returns the value of counter, which is 2 since two instances of the class have been created.

The classmethod() method is useful when you need to define a method that operates on the class itself, rather than on an instance of the class. This can be useful when you need to access class variables or define class-level behavior.