Python classmethod() Function
The classmethod() function in Python is used to define a method that belongs to the class rather than to any specific instance of the class. This means you can access and modify class-level data.
Syntax
classmethod(function)
Parameters:
function– The method you want to convert to a class method.
Returns:
- A method that is bound to the class and not the instance.
Example: Defining a Class Method
class Person:
species = "Human"
def __init__(self, name):
self.name = name
@classmethod
def get_species(cls):
return cls.species
print(Person.get_species())
Human
How It Works
@classmethodis a decorator that makes the method receive the class (cls) as the first argument.- This allows the method to access or modify class-level attributes.
Alternative Without Decorator
class Demo:
def normal_method():
pass
Demo.class_method = classmethod(Demo.normal_method)
Real-World Use Case
Class methods are useful for creating factory methods—methods that return class instances using different input formats.
class Date:
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day
@classmethod
def from_string(cls, date_str):
y, m, d = map(int, date_str.split('-'))
return cls(y, m, d)
d = Date.from_string("2025-05-14")
print(d.year, d.month, d.day)
2025 5 14
Difference Between classmethod() and staticmethod()
| Feature | classmethod() | staticmethod() |
|---|---|---|
| First Parameter | cls (the class) |
None |
| Access to Class Data | Yes | No |
| Typical Use | Factory methods, altering class-level state | Utility methods that don't access class or instance |
Common Mistakes
- Forgetting to use
clsas the first argument in a class method. - Trying to access instance attributes directly—use instance methods for that instead.
Interview Tip
You may be asked to explain the difference between classmethod(), staticmethod(), and regular methods. Practice defining each one!
Summary
classmethod()binds a method to the class, not the instance.- Receives the class as the first argument (
cls). - Useful for factory methods and working with class attributes.
Practice Problem
Create a class Book with a class method from_string() that takes a string like "Title-Author" and returns a new Book object.
class Book:
def __init__(self, title, author):
self.title = title
self.author = author
@classmethod
def from_string(cls, book_str):
title, author = book_str.split('-')
return cls(title, author)
b = Book.from_string("Python101-John Doe")
print(b.title, b.author)
Python101 John Doe
Comments
Loading comments...