classmethod()
classmethod(function) Returns:
classmethod object · Updated March 13, 2026 · Built-in Functions built-in oop class method
The classmethod() function transforms a regular method into a class method. Unlike instance methods, class methods receive the class itself as the first argument (conventionally named cls) instead of the instance (self). This makes them useful for factory methods, alternative constructors, and methods that need to access or modify class-level state.
Syntax
classmethod(function)
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
function | callable | — | A function to be converted into a class method |
Examples
Basic usage
class Counter:
count = 0
def __init__(self):
Counter.count += 1
@classmethod
def get_count(cls):
return cls.count
# Call on the class — no instance needed
print(Counter.get_count()) # 0
a = Counter()
b = Counter()
print(Counter.get_count()) # 2
The @classmethod decorator converts get_count into a method that receives Counter (the class) as its first argument.
Alternative constructor
Class methods shine as factory methods that provide multiple ways to create instances:
from datetime import datetime
class Person:
def __init__(self, name, birth_year):
self.name = name
self.birth_year = birth_year
@classmethod
def from_dict(cls, data):
return cls(data["name"], data["birth_year"])
@classmethod
def from_name(cls, name):
# Assume birth year is current year for simplicity
import datetime
return cls(name, datetime.datetime.now().year)
def age(self):
import datetime
return datetime.datetime.now().year - self.birth_year
# Create from dictionary
p1 = Person.from_dict({"name": "Alice", "birth_year": 1990})
print(p1.name, p1.age()) # Alice 36
# Create from just a name
p2 = Person.from_name("Bob")
print(p2.name, p2.birth_year) # Bob 2026
Accessing class variables
Class methods can read and modify class-level attributes:
class DatabaseConnection:
max_connections = 10
active_connections = 0
def __init__(self):
if DatabaseConnection.active_connections >= DatabaseConnection.max_connections:
raise RuntimeError("Connection limit reached")
DatabaseConnection.active_connections += 1
@classmethod
def get_status(cls):
return f"{cls.active_connections}/{cls.max_connections} connections"
@classmethod
def reset(cls):
cls.active_connections = 0
print(DatabaseConnection.get_status()) # 0/10 connections
conn1 = DatabaseConnection()
print(DatabaseConnection.get_status()) # 1/10 connections
DatabaseConnection.reset()
print(DatabaseConnection.get_status()) # 0/10 connections
Common Patterns
Factory method for parsing
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
@classmethod
def from_tuple(cls, coords):
return cls(coords[0], coords[1])
@classmethod
def from_dict(cls, d):
return cls(d["x"], d["y"])
def to_tuple(self):
return (self.x, self.y)
# Multiple ways to create a Point
p1 = Point.from_tuple((3, 4))
p2 = Point.from_dict({"x": 5, "y": 6})
Implementing singleton pattern
class Singleton:
_instance = None
@classmethod
def get_instance(cls):
if cls._instance is None:
cls._instance = cls()
return cls._instance
s1 = Singleton.get_instance()
s2 = Singleton.get_instance()
print(s1 is s2) # True
classmethod vs staticmethod vs instance method
| Type | First Arg | Can Access | Use Case |
|---|---|---|---|
@classmethod | cls (class) | Class variables, other class methods | Factory methods, class-level operations |
@staticmethod | None | Nothing automatically | Utility functions logically grouped in class |
| Instance method | self (instance) | Instance variables, class | Operations on instances |