Python – classmethod Function Decorator
Python @classmethod is a function decorator that is used to specify a method as a class method.
There is a difference between class method and a regular method inside a class. A class method is a method that belongs to a class rather than an instance of a class.
In this tutorial, we will learn the syntax and usage of classmethod function decorator, with examples.
The syntax of classmethod function decorator is
1. Define a class method
In the following program, we will define a class A, and a class method in it named myFunction().
Run Code Copy
def myFunction(self, msg) :
# Calling on class
# Calling on class instance
Uses of Class Method
The following are some of the common uses of class methods in Python.
- Factory methods: Class methods are commonly used to create objects of a class in a more flexible and convenient way. A class method can create an instance of the class with custom arguments and return it to the caller.
- Alternative constructors: Class methods can be used to define alternative ways of creating instances of a class. For example, a datetime class may have a fromtimestamp class method that creates a datetime object from a Unix timestamp.
- Encapsulation: Class methods can be used to encapsulate logic that operates on the class itself, rather than on its instances. For example, a BankAccount class may have a class method that calculates the total balance across all accounts.
- Inheritance: Class methods can be used to define methods that can be overridden by subclasses, providing a way to implement polymorphism in Python.
- Initialization: Class methods can be used to initialize class-level state or set up class-level configuration.
In this Built-in Functions tutorial, we learned the syntax of the object() built-in function, and how to use this function to create an empty object.