Skip to content

Python classmethod function | Use with example

  • by

Python classmethod function is used to create a class method. It is an inbuilt function that returns the class method for the given function. It takes a single parameter.

classmethod(function)

A class method can be called both by a class and its object. Read more…

Python classmethod function example

Simple example code Create a class method using classmethod().

class App:
    price = 120

    def display(self):
        print('The price is:', self.price)


# create display class method
App.printPrice = classmethod(App.display)

App().display()

Output:

Python classmethod function

Uses classmethod in Python

  1. Generally, it is used to create factory methods. Factory methods return the class object ( similar to a constructor ) for different use cases.
  2. Another uses static methods to create utility functions.

Do comment if you have any doubts or suggestions on this Python function topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading