Updated May 12, 2023
Introduction to Python @classmethod decorator
A class decorator in Python modifies or alters a class or function by using a defined function or class as input. It applies the decorator to the existing class or function, resulting in a modified or altered version of it. The decorator allows the addition of additional operations without permanently changing or modifying the original class or function. The modified class or function can still access the original class or function through calls, allowing for the use of both the altered and original versions.
Syntax:
The basic structure of the Class method decorator is the description of the class decorator where we can use the user-defined function with the self method. Then we have the _call_ method, where we can pass our arguments, and the function where the operation is performed is defined in the final block.
class MyDecorator:
def __init__(self, function):
self.function = function
def __call__(self):
self.function()
@MyDecorator
def function():
print("Beautiful Day")
function()
Output:
How @classmethod decorator Works in Python?
We used the _call_ to define the decorator as a method class in the code. The _call_ method is used when a user creates an object to work as a function, and the decorator will return the object that works like a function. In the above code, we can implement the code or operations we want inside before the call function and after the self. function(). It is possible to completely hide a method from the view of the object since it is using a __call__ method; in that case, the base class will not notice the change in a polymorphic way. The decorators are mostly used to enclose a function with another function to extend the defined function’s dynamic without permanently explicitly modifying the defined function. We can also use the args and kwargs arguments in the decorators using the _call_ method. The arguments args and kwargs will enable us to pass any keywords or arguments in the function, which can be useful in writing the code.
Code:
class MyDecorator:
def __init__(self, function):
self.function = function
def __call__(self, *args, **kwargs):
self.function(*args, **kwargs)
# adding a class decorator to the function
@MyDecorator
def function(name, message ='Hai'):
print("{}, {}".format(message, name))
function("Its a Beautiful Day", "Hai")
Output:
When utilizing a class decorator for performing an operation, you can use the return statement to return the value of the executed operation.
For example,
Code:
class cubeDecorator:
def __init__(self, function):
self.function = function
def __call__(self, *args, **kwargs):
result = self.function(*args, **kwargs)
return result
# implementing class decorator to the function
@cubeDecorator
def get_cube(n):
print("Number:", n)
return n **3
print("Cube value is:", get_cube(10))
Output:
In this example, we performed a cube operation using the class method Decorator, where we mentioned the class method with args and kwargs used as arguments. The result has been returned, so evaluating the function’s output is easy. The Python Class method decorator can be utilized in real-world scenarios for error handling and checking.
The Decorator enables us to study efficiently and denotes the logical errors in the argument, and denotes the error to the user. We can use the try, except method to identify and handle errors in our code that need to be passed to every operation. For example,
Code:
def area_rectangle(l, b):
try:
print(l * b)
except TypeError:
print("area_rectangle Input should be integers")
area_rectangle(2,4)
area_rectangle('four','eight')
Output:
Code:
def area_triangle(b, h):
try:
print(b * h / 2)
except TypeError:
print("area_rectangle Input should be integers")
area_triangle(3,4)
area_triangle('four','eight')
Output:
We used two try-and-accept methods for error handling for two different operations in the above method. This method is time-consuming since we need to specify the error-handling block for our different functions. Instead, using the Class method Decorator, we can perform multiple operations using a single error-handling argument. This method eliminates the need for multiple lines of code, resulting in a clean and organized presentation of the code.
The below example explains the use of error handling using the class decorator method, where we have given a condition that the input of the function we are going to perform should be an integer. Using the args and kwargs argument, we have declared the Type Error message as “Input should be an Integer” to denote the user who could provide string values instead of numbers. Upon running this class, we can run multiple operations or functions where we don’t need to worry about the TypeError from the user since we have informed the user with an exception message.
Code:
def exception_handle(func):
def function(*args, **kwargs):
try:
func(*args, **kwargs)
except TypeError:
print(f"{func.__name__} Input should be integers")
return function
@exception_handle
def area_rectangle(l, b):
print(l * b)
area_rectangle(4, 8)
area_rectangle('four','eight')
@exception_handle
def area_triangle(b, h):
print(b * h / 2)
area_triangle(3,4)
area_triangle('four','eight')
Output:
We can also use the _call_ to define the decorator as a method class in the code to check and identify the error and its most widely used method using a class decorator. In the example below, similar to the previous example, we have performed a square of rectangle operation where we denoted a class name called ErrorCheck, which indicates to the user the kind of error he needs to rectify. Inside the _call_ method, we have denoted the Type Error condition where the user cannot give string values since we perform a numerical operation.
Code:
class ErrorCheck:
def __init__(self, function):
self.function = function
def __call__(self, *params):
if any([isinstance(i, str) for i in params]):
raise TypeError("Input cannot be a string")
else:
return self.function(*params)
@ErrorCheck
def area_rectangle(l, b):
print(l * b)
print(area_rectangle(12, 3))
print(area_rectangle('12', '3'))
Output:
Conclusion
In detail, we have discussed the Python @class method decorator that is most popular in the Python programming platform because of its versatile use for writing user-defined functions and classes where the user can perform multiple operations and alter or modify the function according to the needs. Understanding the Class method decorator comes in very handy during the implementation of various projects.
Recommended Articles
We hope that this EDUCBA information on “Python @classmethod decorator” was beneficial to you. You can view EDUCBA’s recommended articles for more information.