Unlike Static Methods, classmethod in Python bound to a Class. So, we don’t have to create an instance or object of a class to call this class method. A Python classmethod receives cls (class) as an implicit first argument, just like a standard method receives self as the first argument. This cls allows you to access the class variables, methods, and the static methods of the class.
You can define any method as the Python classmethod by using the @classmethod decorator or classmethod() function. Either way, it works, but it is always advisable to go for the first option. The syntax of the Python classmethod is
Class A: @classmethod def function_name(cls, arg1, arg2,....): ........ ...... Or Class A: def function_name(cls, arg1, arg2,....): ........ ...... A.function_name = classmethod(function_name)
You can call the class method using ClassName.MethodName() or ClassName().MethodName(). Both ways will return the classmethod result.
In this section, we show how to create or define a classmethod in Python programming language using @classmethod and classmethod() with examples.
Python classmethod using Decorator
In this example, we are creating a class method called message using the Python @classmethod decorator. Within this method, cls.__name__ returns the class name (Employee), and cls.company returns the class variable company value (Tutorial Gateway).
# Python Class Method class Employee: company = 'Tutorial Gateway' @classmethod def message(cls): print('The Message is From %s Class' %cls.__name__) print('The Company Name is %s' %cls.company) Employee.message() print('-----------') Employee().message() # Other way of calling classmethod
classmethod using the decorator output
The Message is From Employee Class The Company Name is Tutorial Gateway ----------- The Message is From Employee Class The Company Name is Tutorial Gateway
Python classmethod using classmethod() function
Here, we are using the Python classmethod() function to create a class method. From the below Python code, the Employee.printValue = classmethod(Employee.printValue) statement convert the method to the class method.
class Employee: value = 100 def printValue(cls): print('The Value = %d' %cls.value) Employee.printValue = classmethod(Employee.printValue) Employee.printValue()
classmethod function output
The Value = 100
Call Static Method from classmethod in Python
In this example, we show how to call Python Static Methods within the class method. Here, we created a static method called func_msg(), which prints a welcome message. Next, we defined the message class method that returns a class variable company and the class name. Within the same function, we are calling the static method using the cls.methodname.
class Employee: company = 'Tutorial Gateway' @classmethod def message(cls): print('The Company Name is %s' %cls.company) print('The Message is From %s Class' %cls.__name__) cls.func_msg() @staticmethod def func_msg(): print("Welcome to Python Programming") Employee.message()
Here, Instead of printing the message, we are finding the sum and average. First, we created a Static Method that accepts three arguments and returns some of those three. Next, we defined a Python classmethod that calls the static method using the cls. Within the class method, it finds returns the average of static method result.
class Employee: company = 'Tutorial Gateway' @staticmethod def add(a, b, c): return a + b + c @classmethod def avg(cls): x = cls.add(10, 20, 40) return (x / 3) average = Employee.avg() print('The Average Of three Numbers = ', average)
classmethod calling static method output
The Average Of three Numbers = 23.333333333333332
Alter class variable using clasmethod in Python
In this example, we are going to create a Python classmethod that accepts an argument and assigns the value to the class variable. It means, when you call this method, it replaces the company text with the new text that you provide as an argument value. It helps to hide the class variables and allows the end-users to work with the class variable.
class Employee: company = 'Tutorial Gateway' @classmethod def func_newName(cls, new_Name): cls.company = new_Name emp = Employee() print(Employee.company) print(emp.company) print('----------') Employee.func_newName('Python') print(Employee.company) print(emp.company)
Output of altering the class variable using a classmethod
Tutorial Gateway Tutorial Gateway ---------- Python Python
Real-time Examples of classmethod in Python
For example, if the client receives the Employee information in a long string, and details separated by the – (or any other delimiter). Instead of performing splitting operations from his end, we can create a Python class method and allow them to use it.
In this Python classmethod example, we initialized fullname, age, gender, and salary. Next, we created a classmethod that split the given string based on – and returns those values. I suggest you refer to the Python split string article to understand the split function
class Employee: def __init__(self, fullname, age, gender, salary): self.fullname = fullname self.age = age self.gender = gender self.salary = salary @classmethod def func_string_split(cls, employee_str): fullname, age, gender, salary = employee_str.split('-') return cls(fullname, age, gender, salary) emp_from_csv1 = 'Suresh-27-Male-120000' emp_from_csv2 = 'John-29-Male-100000' emp_from_csv3 = 'Tracy-25-Female-155000' emp1 = Employee.func_string_split(emp_from_csv1) print(emp1.fullname) print(emp1.gender) print(emp1.salary) print(emp1.age) print('----------') emp3 = Employee.func_string_split(emp_from_csv3) print(emp3.fullname) print(emp3.gender) print(emp3.age)
classmethod real-time example output
Suresh Male 120000 27 ---------- Tracy Female 25
It is another example of classmethod. Here, we are splitting the date string to Day, Month, and Year. Here, we used the Python map function for this splitting.
class Date: def __init__(self, day = 0, month = 0, year = 0): self.day = day self.month = month self.year = year @classmethod def string_to_Date(cls, string_Date): day, month, year = map(int, string_Date.split('-')) return cls(day, month, year) dt = Date.string_to_Date('31-12-2018') print(dt.day) print(dt.month) print(dt.year)
classmethod and map function output
31 12 2018