Introduction: Python classmethod() Function
When working with Python classes, there are situations where a method needs to work with the class itself instead of a specific object. Whether you’re creating alternative constructors, managing shared class data, or writing cleaner object-oriented code, instance methods are not always the right choice.
Without a built-in solution, you would need extra code to access the class, making programs more complicated than necessary.
A simple solution to these situations is the Python classmethod() Function.
What it is: The classmethod() function is a built-in Python function that converts a regular method into a class method. Unlike an instance method, a class method receives the class itself as its first argument instead of an object instance.
Take a look at a quick example to see how it works.
You can also explore its real-world use cases to learn where it is commonly used.
Now let’s explore its syntax, parameters, return value, and practical examples.
💡 Tip: To explore more built-in functions with practical examples, visit the Python Built-in Functions Learning Guide.
Syntax, Parameters, Return Value and Examples: Python classmethod() Function
The following section explains the syntax, parameters, return value, and a quick example of the Python classmethod() Function.
Syntax
@classmethod
def method_name(cls, ...):
...
or
classmethod(function)
Parameters
| Parameter | Description |
|---|---|
function |
The function that should behave as a class method. |
Return Value
| Return Value | Description |
|---|---|
classmethod |
Returns a class method object that receives the class as its first argument. |
Quick Example
The following example creates and calls a simple class method.
class Student:
school = "ABC School"
@classmethod
def show_school(cls):
print(cls.school)
Student.show_school()
# Output:
ABC School
The @classmethod decorator makes show_school() receive the class as its first argument. This allows the method to access class variables without creating an object.
How the Python classmethod() Function Works
- The
classmethod()function converts a regular method into a class method. - A class method receives
clsas its first parameter. clsrefers to the class, not an object instance.- Class methods can access and modify class variables.
- They can be called using either the class or an object.
Examples: Python classmethod() Function
The following examples show how the Python classmethod() Function works in different programming scenarios.
Example 1: Accessing a Class Variable
class Student:
school = "ABC School"
@classmethod
def show_school(cls):
print(cls.school)
Student.show_school()
# Output:
ABC School
Explanation: The class method receives the class through cls, allowing it to access the class variable school without creating an object.
Example 2: Calling a Class Method Using an Object
class Student:
school = "ABC School"
@classmethod
def show_school(cls):
print(cls.school)
student = Student()
student.show_school()
# Output:
ABC School
Explanation: Although class methods are usually called through the class, they can also be called using an object. Python still passes the class as the first argument.
Example 3: Modifying a Class Variable
class Student:
school = "ABC School"
@classmethod
def change_school(cls, name):
cls.school = name
Student.change_school("XYZ School")
print(Student.school)
# Output:
XYZ School
Explanation: Since cls refers to the class itself, changing a class variable inside the class method updates it for the entire class.
Example 4: Creating an Alternative Constructor
class Student:
def __init__(self, name):
self.name = name
@classmethod
def from_uppercase(cls, name):
return cls(name.upper())
student = Student.from_uppercase("emma")
print(student.name)
# Output:
EMMA
Explanation: A common use of the Python classmethod() Function is creating alternative constructors. Here, the input is converted to uppercase before the object is created.
Example 5: Counting Created Objects
class Student:
count = 0
def __init__(self):
Student.count += 1
@classmethod
def total_students(cls):
print(cls.count)
Student()
Student()
Student()
Student.total_students()
# Output:
3
Explanation: The class method provides a convenient way to display information that belongs to the class rather than to a specific object.
Example 6: Comparing an Instance Method and a Class Method
class Student:
school = "ABC School"
def show_instance(self):
print("Instance Method")
@classmethod
def show_class(cls):
print(cls.school)
student = Student()
student.show_instance()
Student.show_class()
# Output:
Instance Method
ABC School
Explanation: The instance method works with an individual object, while the class method works with the class itself. This makes class methods suitable for tasks involving shared class data.
Example 7: Handling Incorrect Usage
class Student:
@classmethod
def show(cls):
print("Class Method")
try:
Student.show("extra")
except TypeError as e:
print(e)
# Output:
show() takes 1 positional argument but 2 were given
Explanation: The Python classmethod() Function automatically passes the class as the first argument. Providing an extra argument without updating the method definition causes Python to raise a TypeError.
In this example, the exception is handled using a try-except block so the program continues running.
Use Cases: When to use the classmethod() Function
Below are some common situations where the Python classmethod() Function becomes useful:
- Creating alternative constructors.
- Accessing class variables.
- Updating shared class data.
- Managing object counters.
- Building reusable utility methods for a class.
- Writing cleaner object-oriented programs.
Key Takeaways: classmethod() Function
Before wrapping up, here are the key points to remember about the Python classmethod() Function:
- The
classmethod()function converts a regular method into a class method. - A class method receives
clsas its first parameter. clsrepresents the class instead of an object.- Class methods can access and modify class variables.
- They are commonly used as alternative constructors.
- They can be called using either the class or an object.