In this tutorial we will discuss about the classmethod() function in python programming language with the help of examples.
Python classmethod() function
The built-in python function is used to return a class method for the specified function. In newer version of python, you can use the decorator as classmethod() is considered as unpythonic.
You can use the decorator for classmethod definition.
def fun(cls, arg1, arg2, ...):
Parameters of classmethod() function in python
The function in python takes only one argument or parameter i.e., function. A function which is converted into class method.
Return value of Python classmethod() function
The python function is used to return a class method for the specified function.
What is Classmethod?
A class method is that method which is directly bound to a class instead of any object. The is a built-in python function is used to return a class method for the specified function. And we can call a class method from both object and class. And unlike Statismethod, it doesn't require to create a class instance.
Example 1: Creating a simple classmethod
marks = 57
print("Marks obtained : ", obj.marks)
result.obtained = classmethod(result.obtained)result.obtained()
Marks obtained : 57
Example 2: Another example of create class method using classmethod()
name = "Deepak Thakur"
print("The name of best student of the class is : ", obj.name)
Student.stu_name = classmethod(Student.stu_name)Student.stu_name()
The name of best student of the class is : Deepak Thakur
The @classmethod decorator
In newer version of python, you can use the decorator as classmethod() is considered as unpythonic.
Example 3: Creating factory method using class method
name = 'Reena Thakur'
print("Another best student of the class is :",cls.name)Student.stu_name()
Another best student of the class is : Reena Thakur
Difference between Class method and Static method
• Static method deals with parameters whereas the class method deals with the classes. Unlike class method, Static method doesn't know about classes.
• With class method, we can access and modify the class state but it is not possible in static method.
• There is no specific parameter required in static method where the class method takes cls as first parameter.
Example 4: Using staticmethod() and classmethod()
from datetime import date
def __init__(self, name, age):
self.name = name
self.age = age
def details(cls, name, year):
return cls(name, date.today().year - year)
return age > 18
person1 = Person('Deepak', 22)
person2 = Person.details('Reena', 1999)