Python classmethod() Function
classmethod() is a built-in Python function that converts a method into a class method.
A class method belongs to the class rather than an instance; its first parameter is the class itself (usually named cls). Class methods can access class attributes but not instance attributes.
Word meaning: classmethod 是 class method(类方法)的缩写。
Basic syntax and parameters
Syntax format
classmethod(function)
Parameter Description
- Parameter function:
- Type: function object
- Description: the function to convert into a class method.
Function description
- Return Value: returns a class method object.
- Feature: the first parameter is the class itself (cls), not the instance (self).
Example
Example 1: basic usage
Example
class MyClass:
class_attr = 0
@classmethod
def increment(cls):
cls.class_attr += 1
return cls.class_attr
@classmethod
def get_count(cls):
return cls.class_attr
# Call through the class (no instance needs to be created)
print(MyClass.increment()) # Output: 1
print(MyClass.increment()) # Output: 2
print(MyClass.get_count()) # Output: 2
# Can also be called through an instance (but uncommon)
obj = MyClass()
print(obj.increment()) # Output: 3
class_attr = 0
@classmethod
def increment(cls):
cls.class_attr += 1
return cls.class_attr
@classmethod
def get_count(cls):
return cls.class_attr
# Call through the class (no instance needs to be created)
print(MyClass.increment()) # Output: 1
print(MyClass.increment()) # Output: 2
print(MyClass.get_count()) # Output: 2
# Can also be called through an instance (but uncommon)
obj = MyClass()
print(obj.increment()) # Output: 3
Expected output:
1 2 2 3
Code analysis:
- Class methods are defined with the @classmethod decorator.
- The first parameter is cls, representing the class itself.
Example 2: factory methods
Example
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
@classmethod
def from_dict(cls, data):
"""Create an object from a dictionary"""
return cls(data['name'], data['age'])
@classmethod
def from_string(cls, s):
"""Create an object from a string (format: name-age)"""
name, age = s.split('-')
return cls(name, int(age))
def __str__(self):
return f"{self.name}, {self.age} years old"
# Factory pattern using class methods
p1 = Person.from_dict({'name': 'Tom', 'age': 20})
p2 = Person.from_string("Jerry-25")
print(p1) # Output: Tom, 20 years old
print(p2) # Output: Jerry, 25 years old
def __init__(self, name, age):
self.name = name
self.age = age
@classmethod
def from_dict(cls, data):
"""Create an object from a dictionary"""
return cls(data['name'], data['age'])
@classmethod
def from_string(cls, s):
"""Create an object from a string (format: name-age)"""
name, age = s.split('-')
return cls(name, int(age))
def __str__(self):
return f"{self.name}, {self.age} years old"
# Factory pattern using class methods
p1 = Person.from_dict({'name': 'Tom', 'age': 20})
p2 = Person.from_string("Jerry-25")
print(p1) # Output: Tom, 20 years old
print(p2) # Output: Jerry, 25 years old
Expected output:
Tom, 20岁 Jerry, 25岁
Class methods are often used to implement factory methods that create objects from different data sources.
Python3 built-in function