Tutorial Gateway

  • C
  • C#
  • Java
  • Python
  • SQL
  • MySQL
  • Js
  • BI Tools
    • Informatica
    • Talend
    • Tableau
    • Power BI
    • SSIS
    • SSRS
    • SSAS
    • MDX
    • R Tutorial
    • Alteryx
    • QlikView
  • More
    • C Programs
    • C++ Programs
    • Go Programs
    • Python Programs
    • Java Programs

Python classmethod

by suresh

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 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
Python Classmethod Example 1

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()
Python Classmethod Example 2

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()
Python Classmethod Example 3

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)
Python Classmethod Example 4

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)
Python Classmethod Example 5

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.

TIP: 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)
Python-Classmethod-Example-6

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)
Python Classmethod Example 7

Placed Under: Python

  • Download and Install Python
  • Python Arithmetic Operators
  • Python Assignment Operators
  • Python Bitwise Operators
  • Python Comparison Operators
  • Python Logical Operators
  • Python If Statement
  • Python If Else
  • Python Elif Statement
  • Python Nested If
  • Python For Loop
  • Python While Loop
  • Python Break
  • Python Continue
  • Python Dictionary
  • Python datetime
  • Python String
  • Python Set
  • Python Tuple
  • Python List
  • Python List Comprehensions
  • Python Lambda Function
  • Python Functions
  • Python Types of Functions
  • Python Iterator
  • Python File Handling
  • Python Directory
  • Python Class
  • Python classmethod
  • Python Inheritance
  • Python Method Overriding
  • Python Static Method
  • Connect Python and SQL Server
  • Python SQL Create DB
  • Python SQL Select Top
  • Python SQL Where Clause
  • Python SQL Order By
  • Python SQL Select Statement
  • Python len Function
  • Python max Function
  • Python map Function
  • Python print Function
  • Python sort Function
  • Python range Function
  • Python zip Function
  • Python Math Functions
  • Python String Functions
  • Python List Functions
  • Python NumPy Array
  • NumPy Aggregate Functions
  • NumPy Arithmetic Operations
  • Python Numpy Bitwise operators
  • Numpy Comparison Operators
  • Numpy Exponential Functions
  • Python Numpy logical operators
  • Python numpy String Functions
  • NumPy Trigonometric Functions
  • Python random Array
  • Python numpy concatenate
  • Python numpy Array shape
  • Python pandas DataFrame
  • Pandas DataFrame plot
  • Python Series
  • Python matplotlib Histogram
  • Python matplotlib Scatter Plot
  • Python matplotlib Pie Chart
  • Python matplotlib Bar Chart
  • Python List Length
  • Python sort List Function
  • Python String Concatenation
  • Python String Length
  • Python substring
  • Python Programming Examples

Copyright © 2021 · All Rights Reserved by Suresh

About Us | Contact Us | Privacy Policy