Sobes.tech
Junior — Middle

How does the @classmethod decorator in Python work and what role does it play in class methods?

sobes.tech AI

Answer from AI

The @classmethod decorator in Python is used to define a class method that receives the class itself as the first argument, rather than an instance of the class (self). This allows the method to work with the class and its attributes, rather than with a specific object.

Main features:

  • A class method can be called on both an instance and the class itself.
  • It allows creating alternative constructors or methods that affect the class as a whole.

Example:

class MyClass:
    count = 0

    def __init__(self):
        MyClass.count += 1

    @classmethod
    def get_count(cls):
        return cls.count

    @classmethod
    def create_with_value(cls, value):
        obj = cls()
        obj.value = value
        return obj

# Usage
print(MyClass.get_count())  # 0
obj1 = MyClass()
obj2 = MyClass.create_with_value(10)
print(MyClass.get_count())  # 2

Thus, @classmethod allows methods to work with the class itself, rather than with individual instances.