logo

Class Methods with @classmethod

Regular methods take self and work on instances. Class methods take cls and work on the class itself.

class User:
    count = 0

    def __init__(self, name):
        self.name = name
        User.count += 1

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

Call class methods on the class, not an instance:

print(User.get_count())  # 0
alice = User("Alice")
print(User.get_count())  # 1

Class methods are often used as alternative constructors - different ways to create objects.

I explain class methods in my Python OOP course.