Python is an object-oriented language. Various methods are there in python which are attached with the class. There is a built-in function defined in Python regarding the definition of the method not depending on the creation of the object of the class. This function is python classmethod. This is the function that is bound to the class rather than its object instance. Also, it does not require the creation of a class instance i.e. object. Hence it is similar to static method.
There are many built-in methods in Python that return a class object (like a constructor) for different use cases. These are termed Factory methods. This feature is similar to function overloading in the C++ language. Also, python does not have anything as such, classmethods and staticmethods are commonly used.
The Python classmethod() is the built-in function, which is used to return the class method for the given function.
Class and its object both can call the classmethod. Since the classmethod() is bound to the class and not to any instance of the class. So, a class method for the class can be invoked without the existence of an object for that class.
It is having two variants of syntax. These are,
Also, irrespective of the matter, the class method is always attached to the class with the first argument as the class itself i.e. cls.
@classmethod decorator can be used in python for creating the class method. Syntax of decorator classmethod() is as follows:
def fun(cls, arg1, arg2, …):
Here, fun is the name of the defined function which needs to be converted to the class method. And arg1, arg2 … are the various arguments.
Python classmethod() Parameters:
A classmethod is accepting “cls” as the first parameter. A classmethod has the access to the class and also it can modify the class state. Also, every classmethod must have class as its parameter. On the other hand, the staticmethod() function accepts only a single parameter:
Return value from classmethod():
Classmethod function is returning the converted class method. In other words, it returns a class method for the given function.
What is a class method?
A class method is a function, which is always bound to the class instead of its object. Thus, it has no requirement for the creation of any class instance. But, this is not the case with static method. Class methods are working with the class, as their parameter is always the class itself. Whereas, static methods are not knowing about the class and hence are dealing with the parameters. The class method is being called by the class and its object both. It is having cls or self parameters, which are not in the case of a static method.
Correct instance creation in inheritance:
While deriving a class through the implementation of a factory method as a class method, will ensure the correct instance creation of the derived class. One can create a static method, but the object it creates will always be hardcoded as a Base class. In the case of the python classmethod the scenario is different.
When we use a class method, it will create the correct instance of its derived class. Using the class method for the base class we can ensure the OOP-ness of the code. This is because it takes the first parameter as the class itself and calls its factory method for the purpose.
Example 1: Create a class method using classmethod() function:
In this example, we will see the way to create classmethod. Here, we created a class with a “testing” name having one member variable “subject”. Also, we created a function “display” which prints the object.
Now we passed the method “testing.display” into classmethod. Further it converts the methods to a class method. Then we call the class function display without creating a function object.
#Python program to explain classmethod() # creation of class class testing: subject = “CS” def display(obj): # creation of function print("Subject name : ", obj.subject) testing.display = classmethod(testing.display) testing.display() Output: Subject name: CS
Example 2: Python program to understand the python classmethod:
# creation of variable
name = “smart boy”
# creation of function
print(“The name of student is : “, obj.name)
# creation of display classmethod
student.display_name = classmethod(student.display_name)
# Furthe this method will be termed as classmethod
# display_name() method is termed as a class method
The name of student is: smart boy
Example 3: Factory method using the Classmethod:
The @classmethod decorator is the built-in function. It is an expression that will be evaluated after defining the function. The result of this evaluation will make a shadow for the function definition. A class method receives implicitly the class as its first argument. This is similar to the instance method that receives the instance.
Another method for defining the classmethod is by using the @classmethod decorator. Classmethod() function is used for various factory design patterns. This helps when one wants to call many functions with the class name and not with the object.
# Python program to demonstrate the use of @classmethod
# It will use the class method and static method.
from datetime import date
def __init__(self, name, years):
self.name = name
self.years = years
# a class method to create the employee object by the joining year.
def fromJoiningYear(cls, name, years):
return cls(name, date.today().year – years)
print(“Name of the employee is: “, self.name, ” Total service years : “, self.years)
employee = Employee(“Sarthak”, 10)
Name of the employee is: Sarthak Total service years : 10
Frequently Asked Questions:
Q1. What is an instance in Python?
Answer: An individual object of a certain class is termed an instance of the class. An object obj that belongs to a class Square, for example, is the instance of the class Square. Therefore, An instance, in object-oriented programming is the specific realization of any class.
Q2. What is the difference between classmethod and ctaticmethod in Python?
|Class method||Static method|
|Classmethods are related to a class with access to all class-specific data.||Staticmethods are related to a class without the need to access any class-specific data.|
|It takes “cls” as a parameter, pointing to the class but not to the instance of the class.||It is not receiving any implicit first argument like self or cls.|
|These methods can access or modify the class state.||These methods have no privilege to access or modify the class state.|
|One may use the @classmethod decorator to create a class method.||One may use the @staticmethod decorator to create a static method.|
|The class method may be used to define the factory method returning the class instances.||The static method is not able to return a class object.|
Q3. What does “cls” mean in Python?
Answer: In python “cls” implies that the method belongs to the class. Whereas, “self” implies that the method is related to an instance of the class. Thus members with “cls” can be accessed by class name. On the other hand, the one with “self” can be accessed by an instance of the class.