Decorators are a very powerful and useful tool in Python since it allows programmers to modify the behaviour of function or class. Decorators allow us to wrap another function in order to extend the behaviour of the wrapped function, without permanently modifying it.
We can define a decorator as a class in order to do that, we have to use a
__call__ method of classes. When a user needs to create an object that acts as a function then function decorator needs to return an object that acts like a function, so
__call__ can be useful. For Example
Class Decorator with
In order to use class decorator with argument
**kwargs we used a
__call__ function and passed both the argument in a given function
Class Decorator with return statement :
In the given example the functions did not return anything so there is not any issue, but one may need the returned value. So we use return statement with the class decorator.
given number is: 195 Square of number is: 38025
Using class Decorators to print Time required to execute a program :
In order to print time required to execute a program, we use
__call__ function and use a time module so that we can get a execute time of a program
Execution took 3.003122091293335 seconds
Checking error parameter using class decorator :
This type of class decorator is most frequently used. This decorator checks parameters before executing the function preventing the function to become overloaded and enables it to store only logical and necessary statements.
6 TypeError: parameter cannot be a string !!
- Data Classes in Python | Set 2 (Decorator Parameters)
- self in Python class
- First Class functions in Python
- String Template Class in Python
- Class or Static Variables in Python
- Class & Instance Attributes in Python
- Changing Class Members in Python
- How to create a list of object in Python class
- Python | Using variable outside and inside the class and method
- CBSE Class 11 | Computer Science - Python Syllabus
- Python | Avoiding class data shared among the instances
- CBSE Class 12 | Computer Science - Python Syllabus
- Python Tkinter | Create different shapes using Canvas class
- Python Tkinter | Create different type of lines using Canvas class
- Object Oriented Programming in Python | Set 1 (Class, Object and Members)
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.