classmethod() in Python



classmethod() in Python

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

Syntax: classmethod(function)

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

Return Type:This function returns the converted class method.

You can also use @classmethod decorator for classmethod definition.

Syntax: 

@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.

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

  • A class method takes cls as the first parameter while a static method needs no specific parameters.
  • A class method can access or modify the class state while a static method can’t access or modify it.
  • In general, static methods know nothing about the class state. They are utility-type methods that take some parameters and work upon those parameters. On the other hand class methods must have class as a parameter.
  • We use @classmethod decorator in python to create a class method and we use @staticmethod decorator to create a static method in python.

Example of classmethod in Python

Example 1: Create a simple classmethod

In this example, we are going to see a how to create classmethod, for this we created a class with geeks name with member variable course and created a function purchase which prints the object.

Now we passed the method geeks.purchase into classmethod which converts the methods to a class method and then we call the class function purchase without creating a function object.

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

Output:

Puchase course :  DSA

Example 2: Create class method using classmethod()

# Python program to understand the classmethod
 
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

Example 3: Factory method using 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

The @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:

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 which 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 the instances.

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
25
True

 

Last Updated on October 28, 2021 by admin

Leave a Reply

Your email address will not be published. Required fields are marked *

Recommended Blogs