@classmethod Function Decorator
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.
Syntax
The syntax of classmethod function decorator is
class SomeClassName:
@classmethod
def funcitonName():
pass
Examples
1. Define a class method
In the following program, we will define a class A, and a class method in it named myFunction().
Python Program
class A:
@classmethod
def myFunction(self, msg) :
print(msg)
# Calling on class
A.myFunction('Hello World!')
# Calling on class instance
A().myFunction('Hello User!')
Output
Hello World!
Hello User!
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 afromtimestamp
class method that creates adatetime
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.
Summary
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.