Python 3x Pandas Django

@classmethod & @staticmethod


Before you start this section, you must first understand how @decorators work.

What is a class method?

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

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

This method used @classmethod and the syntax is,

Syntax

@classmethod
def func(cls, args...)

What is a static method?

The staticmethod() built-in function in python, which returns a static method for a given function.

This method used @staticmethod and the syntax is,

Syntax

@staticmethod
def func(args...)

Static Method vs Class Method

> Class method works with the class since its parameter is always the class itself.

> Static method knows nothing about the class and just deals with the parameters.

> Class method use @classmethod decorator and static method use @staticmethod.

> Both the methods can be called both by the class and its objects.

Example 1 @classmethod:

class VotingAge:
    age = 18

    @classmethod
    def printVotingAge(cls):
        print('Minimum voting age is:', cls.age)

VotingAge.printVotingAge()   #Minimum voting age is: 18

obj1 = VotingAge()
obj1.printVotingAge()        #Minimum voting age is: 18

Output:

Minimum voting age is: 18
Minimum voting age is: 18

In the above exmaple, we have created a class VotingAge, with a member variable age and function printVotingAge that takes a single parameter cls and this function is decorator with @classmethod.

We call class method with\without creating a class object.

VotingAge.printVotingAge()
        or
obj1 = VotingAge()
obj1.printVotingAge()

Example 2 @staticmethod:

from datetime import date

class Vaccination:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    @staticmethod
    def isVaccinationAllowed(age):
        return age > 18

print (Vaccination.isVaccinationAllowed(10))  #False
print (Vaccination.isVaccinationAllowed(19))  #True

Output:

False
True

Example 3:

from datetime import date

class Vaccination:
    def __init__(self, name, age):
        self.name = name
        self.age = age

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

    @staticmethod
    def isVaccinationAllowed(age):
        return age > 18

Persion1 = Vaccination('Persion1', 21)
Persion2 = Vaccination.findAge_BirthYear('Persion2', 2008)

print (Persion1.age)        #21
print (Persion2.age)        #13

print (Vaccination.isVaccinationAllowed(Persion1.age))  #True
print (Vaccination.isVaccinationAllowed(Persion2.age))  #False

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

If you have any doubts or queries related to this chapter, get them clarified from our Python Team experts on ibmmainframer Community!