Open In App

classmethod() in Python

The classmethod() is an inbuilt function in Python, which returns a class method for a given function.

classmethod() in Python Syntax

Syntax: classmethod(function)



Parameter :This function accepts the function name as a parameter.

Return Type:This function returns the converted class method.



Python classmethod() Function

The classmethod() methods are bound to a class rather than an object. Class methods can be called by both class and object. These methods can be called with a class or with an object. 

Class Method vs Static Method

The basic difference between the class method vs Static method in Python and when to use the class method and static method in Python.

Example of classmethod in Python

Create a simple classmethod

In this example, we are going to see how to create a class method in Python. For this, we created a class named “Geeks” with a member variable “course” and created a function named “purchase” which prints the object. Now, we passed the method Geeks.purchase into a class method using the @classmethod decorator, which converts the method to a class method. With the class method in place, we can call the function “purchase” without creating a function object, directly using the class name “Geeks.”




class geeks:
    course = 'DSA'
 
    def purchase(obj):
        print("Purchase course : ", obj.course)
 
 
geeks.purchase = classmethod(geeks.purchase)
geeks.purchase()

Output
Purchase course :  DSA


Create class method using classmethod()

Created print_name classmethod before creating this line print_name() It can be called only with an object not with the class now this method can be called as classmethod print_name() method is called a class method.




class Student:
 
    # create a variable
    name = "Geeksforgeeks"
 
    # create a function
    def print_name(obj):
        print("The name is : ", obj.name)
 
 
# create print_name classmethod
# before creating this line print_name()
# It can be called only with object not with class
Student.print_name = classmethod(Student.print_name)
 
# now this method can be called as classmethod
# print_name() method is called a class method
Student.print_name()

Output
The name is :  Geeksforgeeks


Factory method using a Class method

Uses of classmethod() function are used in factory design patterns where we want to call many functions with the class name rather than an object.




# Python program to demonstrate
# use of a class method and static method.
from datetime import date
 
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
 
    # a class method to create a
    # Person object by birth year.
    @classmethod
    def fromBirthYear(cls, name, year):
        return cls(name, date.today().year - year)
 
    def display(self):
        print("Name : ", self.name, "Age : ", self.age)
 
person = Person('mayank', 21)
person.display()

Output
Name :  mayank Age :  21


How the class method works for the inheritance?

In this example, we are making Python class hierarchy with two classes, Person and Man, and demonstrates the usage of class methods and inheritance.




from datetime import date
 
# random Person
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
 
    @staticmethod
    def from_FathersAge(name, fatherAge, fatherPersonAgeDiff):
        return Person(name, date.today().year - fatherAge + fatherPersonAgeDiff)
 
    @classmethod
    def from_BirthYear(cls, name, birthYear):
        return cls(name, date.today().year - birthYear)
 
    def display(self):
        print(self.name + "'s age is: " + str(self.age))
 
class Man(Person):
    sex = 'Female'
 
man = Man.from_BirthYear('John', 1985)
print(isinstance(man, Man))
 
man1 = Man.from_FathersAge('John', 1965, 20)
print(isinstance(man1, Man))

Output
True
False


Python @classmethod Decorator

The @classmethod decorator is a built-in function decorator which is an expression that gets evaluated after your function is defined. The result of that evaluation shadows your function definition. A class method receives the class as the implicit first argument, just like an instance method receives the instance.

Syntax of classmethod Decorator

class C(object):  

   @classmethod

      def fun(cls, arg1, arg2, …):

       ….

Where,

  • fun: the function that needs to be converted into a class method
  • returns: a class method for function.

Note:

Example 

In the below example, we use a staticmethod() and classmethod() to check if a person is an adult or not.




# Python program to demonstrate
# use of a class method and static method.
from datetime import date
 
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
 
    # a class method to create a
    # Person object by birth year.
    @classmethod
    def fromBirthYear(cls, name, year):
        return cls(name, date.today().year - year)
 
    # a static method to check if a
    # Person is adult or not.
    @staticmethod
    def isAdult(age):
        return age > 18
 
person1 = Person('mayank', 21)
person2 = Person.fromBirthYear('mayank', 1996)
 
print(person1.age)
print(person2.age)
 
# print the result
print(Person.isAdult(22))

Output
21
27
True



Article Tags :