Python classmethod() Function
classmethod()It is a built-in function in Python used to convert a method into a class method.
A class method is a method that belongs to the class rather than the instance; its first parameter is the class itself (usually named cls). Class methods can access class attributes but cannot access instance attributes.
Word Definitions: classmethod 是 class method(类方法)的缩写。
Basic Syntax and Parameters
Syntax Format
classmethod(function)
Parameter Description
- Parameter function:
- Type: Function object
- Description: The function to be converted to a class method.
Function Description
- Return value: Returns a class method object.
- Features: The first parameter is the class itself (cls), not the instance (self).
Examples
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
# Called via the class (no instance creation needed)
print(MyClass.increment()) # Output: 1
print(MyClass.increment()) # Output: 2
print(MyClass.get_count()) # Output: 2
# Can also be called via 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
# Called via the class (no instance creation needed)
print(MyClass.increment()) # Output: 1
print(MyClass.increment()) # Output: 2
print(MyClass.get_count()) # Output: 2
# Can also be called via an instance (but uncommon)
obj = MyClass()
print(obj.increment()) # Output: 3
Expected Output:
1 2 2 3
Code Explanation:
- Class methods are defined using the @classmethod decorator.
- The first parameter is cls, which represents the class itself.
Example 2: Factory Method
Example
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
@classmethod
def from_dict(cls, data):
"""Create object from dictionary"""
return cls(data['name'], data['age'])
@classmethod
def from_string(cls, s):
"""Create object from 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 object from dictionary"""
return cls(data['name'], data['age'])
@classmethod
def from_string(cls, s):
"""Create object from 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 commonly used to implement factory methods for creating objects from different data sources.
Other Extensions
Python3 Built-in Functions