Python classmethod() built-in function
From the Python 3 documentation
Transform a method into a class method. A class method receives the class as an implicit first argument, just like an instance method receives the instance.
Introduction
A classmethod
is a method that is bound to the class and not the instance of the class. It takes the class itself as its first argument, conventionally named cls
. This is in contrast to a regular instance method, which takes the instance as its first argument (self
).
They are often used for factory methods that create instances of the class in a specific way.
Example
Here’s a common use case: creating a factory method that can instantiate the class from a different data format, like a dictionary.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
@classmethod
def from_dict(cls, data):
# This is a factory method that creates a Person instance from a dictionary
return cls(data['name'], data['age'])
def display(self):
print(f"Name: {self.name}, Age: {self.age}")
# Data for a new person
person_data = {'name': 'John', 'age': 30}
# Create a Person instance using the class method
p = Person.from_dict(person_data)
p.display()
# Output: Name: John, Age: 30