Python @classmethod
: Work with Class-Level Data
A @classmethod
lets you define methods that belong to the class, not an instance. It’s useful when you need to access or modify class-level data or create alternative constructors.
Simple Example
class Example:
value = 10 # Class-level attribute
@classmethod
def show(cls):
return cls.value
print(Example.show()) # Output: 10
This method belongs to the class itself, not an instance.
Syntax
class ClassName:
@classmethod
def method_name(cls, args):
# Class-level logic
- @classmethod → Marks the method as a class method.
- cls → Refers to the class itself, not an instance.
1. Creating Alternative Constructors
@classmethod
is useful when you want different ways to create objects.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
@classmethod
def from_birth_year(cls, name, birth_year):
return cls(name, 2025 - birth_year)
person = Person.from_birth_year("Alice", 1995)
print(person.name, person.age) # Output: Alice 30
This allows you to create an object using a birth year instead of age.
2. Modifying Class-Level Data
A @classmethod
is perfect for updating shared class attributes.
class Counter:
count = 0
@classmethod
def increment(cls):
cls.count += 1
Counter.increment()
Counter.increment()
print(Counter.count) # Output: 2
This updates a class-level counter instead of modifying instance data.
How to Use @classmethod
(Short & Simple Guide)
- ✔ Use
@classmethod
when working with the class itself, not an instance. - ✔ Always use
cls
as the first parameter (it refers to the class). - ✔ Use it for alternative constructors and class-level data.
Key Notes
- ✔ Works on the class itself, not instances.
- ✔ Great for alternative constructors (e.g.,
from_birth_year
). - ✔ Modifies shared class attributes across instances.
- ✔ Avoids instance-specific changes, making code more structured.
Using @classmethod
helps keep class logic clean and reusable, making your code more efficient and organized. 🚀