Unlike Static Methods, classmethod in Python are 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 normal method receives self as the first argument. This cls allows you 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 ways will work but it is always advisable to go for the first option. Before we get into the example, let me show you the syntax of the Python classmethod is as shown below
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 article, we will show you, 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
Python classmethod using classmethod() function
Here, we are using the Python classmethod() function to create a class method. From the below code, Employee.printValue = classmethod(Employee.printValue) statement will convert the method to class method.
class Employee: value = 100 def printValue(cls): print('The Value = %d' %cls.value) Employee.printValue = classmethod(Employee.printValue) Employee.printValue()
Call Static Method from classmethod in Python
In this example, we will show you, how to call a Python Static Methods within the class method. Here, we created a static method called func_msg() which prints 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)
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 will replace the company text with the new text that you provide as an argument value. This 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)
Real-time Examples of classmethod in Python
For example, if our client is receiving the Employee information in a long string, and the details are 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 initialised fullname, age, gender and salary. Next, we created a classmethod that will split the given string based on – and returns those values.
TIP: I suggest you to 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)
This is an another example of the Python 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)