Introduction to Python @classmethod decorator
Class Decorator can be defined as an object in python that can be called to modify or alter a class or a function which is used in the code with a defined function or a defined class that would be passed into the decorator in-order to return an altered or modified class or function that has been defined before or in other words decorators permits us to overwrite another function inside a defined function to include more operations without altering or changing the function permanently and calls are available for altered or modified function and classes to call the original class or function.
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 and then comes the _call_ method where we can pass our arguments and then the function where we are performing our operation is mentioned at 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 have 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 our code or operations we want inside before the call function and also 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, and 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 of 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 number of keywords or arguments in the function, which can be very 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 an operation is needed to be performed using the class decorator, we can use the return statement, which will return the value of the operation that has been executed.
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 have mentioned the class method with args and kwargs that are used as arguments. The result has been returned so that it is easy for evaluating the output of the function. In a real-world scenario, the Python Class method Decorator is used in error handling and checking. The Decorator enables us to efficiently check 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 except 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 different operations we use. Instead, if we use the Class method Decorator, we can perform multiple operations by using a single error handling argument. This method avoids multiple lines of codes, and the code can be presented in a neat and orderly manner.
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 in 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 the user about the kind of error that he needs to rectify. Inside the _call_ method, we have denoted the Type Error condition where the user is not allowed to give string values since we are performing 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 can alter or modify the function according to the needs. Understanding Class method decorator comes in very handy during the implementation of various projects.
Recommended Articles
This is a guide to Python @classmethod decorator. Here we also discuss the introduction and how @classmethod decorator works in python? Along with different examples and their code implementation. You may also have a look at the following articles to learn more –
40 Online Courses | 13 Hands-on Projects | 215+ Hours | Verifiable Certificate of Completion
4.8
View Course
Related Courses