Decorators
What Are Decorators?
- In Python, a decorator is a special type of function used to modify the behavior of another function.
Define a Decorator Function:
A decorator takes a function as input, adds some functionality to it, and returns the modified function.
pythondef mydecorator(fn): def inner_function(): print('Hello! ', end='') fn() return inner_function
Applying a Decorator to a Function:
Decorators are applied using the "@" symbol just above the function to be decorated.
python@mydecorator def greet(): print('Good morning!') greet()Output:
Hello! Good morning!
Decorator with Arguments:
Decorators can accept arguments and pass them to the decorated function.
pythondef mydecorator(fn): def inner_function(*args, **kwargs): print('Hello! ', end='') fn(*args, **kwargs) return inner_function @mydecorator def greet(name): print(name) greet('Ram!')Output:
Hello! Ram!
Uses of Decorators:
- Decorators can be used for various purposes such as logging, timing, authentication, etc.
Types of Decorators:
- Function Decorators: Most common, applied to functions.
- Class Decorators: Modify the behavior of a class.
- Method Decorators: Applied to methods within a class.
- Property Decorators: Applied to class properties.
Exercises:
- Create a Simple Decorator:
Define a decorator that prints "Start" before and "End" after calling the decorated function.
pythondef mydecorator(fn): def inner_function(): print("Start") fn() print("End") return inner_function @mydecorator def greet(): print('Hello!') greet()Output:
Start Hello! End
- Decorator with Arguments:
Create a decorator that prints a custom message before calling the decorated function.
pythondef mydecorator(fn): def inner_function(message): print(message) fn() return inner_function @mydecorator def greet(): print('Hello!') greet('Welcome!')Output:
Welcome! Hello!
Summary:
- Decorators are powerful tools in Python for modifying function behavior without changing the function's code. They are used for adding features, logging, timing, and more. Practice creating and using decorators to master this concept!