Sobes.tech
Junior — Middle

What is the purpose of the @classmethod decorator in Python and how does it differ from regular class methods?

sobes.tech AI

Answer from AI

The @classmethod decorator in Python is used to define a method that receives the class itself as the first argument, rather than an instance of the class (self). Such a method can access class attributes and other class methods, not specific object data.

Differences from regular methods:

  • Regular methods take self as the first parameter — a reference to the specific instance.
  • Methods with @classmethod take cls as the first parameter — the class itself.

This is useful when you need to create alternative constructors or methods that operate on the class as a whole, rather than on a particular object.

Example:

class MyClass:
    count = 0

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

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

obj1 = MyClass()
obj2 = MyClass()
print(MyClass.get_instance_count())  # Outputs: 2

Here, get_instance_count is a class method that accesses the class attribute count.