Tutorial Study Image

Python classmethod()

Normally to call a method of a class, we need to first create an instance or object of the class. But a class method is bound to the class, not to its objects, so the creation of the classmethod function returns the class method for a given function


classmethod(function) #where function is an name of function

classmethod() Parameters:

The classmethod() function takes only a single parameter

Parameter Description Required / Optional
A function The function that is to be converted to the class method Required

classmethod() Return Value

The return value or output of the method is a class method, which can be called without an instance of the class.

Input Return Value
Function Returns the class method for the passed function

Examples of classmethod() method in Python

Example 1: How to create a class method?


class Products:
getcode = ‘P36’

def getProductCode(cls):
print('The Product Code is:', cls.getcode)

# create printCode class method
Products.getProductCode = classmethod(Products .getProductCode ) 
Products.getProductCode ()
 

Output:

The Product Code is: P36

Example 2: How to create a factory method using the class method?


# random Person
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    @classmethod
    def fromBirthYear(cls, name, birthYear):
        return cls(name, date.today().year - birthYear)

    def display(self):
        print(self.name + "'s age is: " + str(self.age))
 pers 19)
person.display()
 pers  1985)
person1.display()
 

Output:

Adam's age is: 19
John's age is: 31

Example 3: How the class method works for the inheritance?


from datetime import date

# random Person
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    @staticmethod
    def fromFathersAge(name, fatherAge, fatherPersonAgeDiff):
        return Person(name, date.today().year - fatherAge + fatherPersonAgeDiff)

    @classmethod
    def fromBirthYear(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 = 'Male'

man = Man.fromBirthYear('John', 1985)
print(isinstance(man, Man))

man1 = Man.fromFathersAge('John', 1965, 20)
print(isinstance(man1, Man))
 

Output:

True
False