classmethod() in Python

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

Syntax: classmethod(function)

Parameter :This function accept function name as parameter.



Return Type:This function returns converted class method.

classmethod() methods are bound to class rather than an object. Class methods can be called by both class and object. These methods can be call with class or with object. Below examples illustrates above clearly.

Example #1:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

The name is :  Geeksforgeeks

 
Example #2:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to understand classmethod
  
class Subject:
      
    # creating a variable
    favorite_subject = "Networking"
      
    # creating a function
    def favorite_subject_name(obj):
        print("My favorite_subject_name is : ",
                           obj.favorite_subject)
          
# creating favorite_subject_name classmethod
# before creating this line favorite_subject_name()
# can be called only with object not with class
Subject.favorite_subject_name = classmethod(Subject.favorite_subject_name)
  
# now this method can be call as classmethod
# favorite_subject_name() method is called as class method
Subject.favorite_subject_name()

chevron_right


Output:

My favorite_subject_name is :  Networking

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

 
The @classmethod Decorator:

The @classmethod decorator, is a builtin function decorator that 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 implicit first argument, just like an instance method receives the instance.

Syntax:

class C(object):
    @classmethod
    def fun(cls, arg1, arg2, ...):
       ....

fun: function that needs to be converted into a class method
returns: a class method for function.
  • 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 will be applicable to all the instances.

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

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to demonstrate 
# use of 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))

chevron_right


Output:

21
22
True


My Personal Notes arrow_drop_up

All powers are within you You can do anything and everything Believe in that

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.