search

What is the use of the "classmethod" decorator in Python?

The "classmethod" decorator in Python is used to define a method that operates on the class rather than on instances of the class. It is declared with the **@classmethod** syntax above a method definition within a class. The first argument of a classmethod is always the class itself, represented by **cls**. The **classmethod** decorator allows you to modify the class state, rather than instances of the class. This can be useful for factory methods that create instances of the class based on arguments, or for alternative constructors. For example:

class Circle:
    pi = 3.14

    def __init__(self, radius):
        self.radius = radius

    @classmethod
    def from_diameter(cls, diameter):
        return cls(diameter / 2)

    @classmethod
    def from_area(cls, area):
        radius = (area / cls.pi)**0.5
        return cls(radius)

    def area(self):
        return self.pi * self.radius**2

Related Questions You Might Be Interested