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:
- A class method is a method that is bound to the class and not the object of the class.
- They have the access to the state of the class as it takes a class parameter that points to the class and not the object instance.
- It can modify a class state that would apply across all the instances of the class. For example, it can modify a class variable that would be applicable to all instances.
Example
In the below example, we use a staticmethod() and classmethod() to check if a person is an adult or not.
Python3
# 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 )) |
21 27 True
classmethod() in Python
The classmethod() is an inbuilt function in Python, which returns a class method for a given function.