In Python, class methods are methods that work on the class itself, not just its instances.
They are defined using the @classmethod
decorator, and the first parameter is always cls
(a reference to the class).
Example 1: Basic Class Method
class Example:
@classmethod
def describe_class(cls):
return f"This is the {cls.__name__} class."
print(Example.describe_class()) # Output: This is the Example class.
Here,
- The
@classmethod
decorator tells Python thatdescribe_class
is a class method. - The first argument
cls
refers to the class, not an object. - You can call it directly on the class (
Example.describe_class()
), without creating an instance.
Why Use Python Class Methods?
Class methods are useful in these cases:
- Factory Methods: To create objects with special logic.
- Alternative Constructors: To allow multiple ways to create objects.
- Class-level Utilities: For operations that relate to the class, not just instances.
Example 2: Factory Method
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
@classmethod
def from_birth_year(cls, name, birth_year):
age = 2025 - birth_year
return cls(name, age)
# Create object using normal constructor
p1 = Person("Alice", 30)
# Create object using class method (alternative constructor)
p2 = Person.from_birth_year("Bob", 2000)
print(p1.name, p1.age) # Output: Alice 30
print(p2.name, p2.age) # Output: Bob 25
Here,
from_birth_year
is a class method that calculates age from birth year.- Instead of writing
Person("Bob", 25)
, you can callPerson.from_birth_year("Bob", 2000)
. - This makes the code cleaner and allows multiple ways to create objects.
👉 Next tutorial: Python Class Methods as Alternative Constructors