Python decorators are a powerful and useful feature that allows you to modify the behavior of functions or methods. They are often used for logging, enforcing access control, or adding functionality to existing functions without modifying their code.
What is a Decorator?
A decorator in Python is a design pattern that allows you to add new functionality to an existing object without modifying its structure. Decorators are very useful for managing cross-cutting concerns such as logging, security, caching, and validation.
Example of a Simple Decorator
Here's an example of a simple decorator that prints a message before and after the execution of a function:
def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
When you run the say_hello()
function, the output will be:
Something is happening before the function is called.
Hello!
Something is happening after the function is called.
Types of Decorators
There are two main types of decorators in Python:
- Function Decorators: These are used to wrap a function with another function.
- Class Decorators: These are used to wrap a function with a class.
Function Decorators
Function decorators are the most common type of decorators in Python. They are defined using the @decorator_name
syntax.
Class Decorators
Class decorators are less common but can be very powerful. They are defined using a class that implements the __call__
method.
Using Decorators with Classes
Here's an example of a class decorator:
def my_class_decorator(cls):
class NewClass(cls):
def __init__(self, *args, **kwargs):
super(NewClass, self).__init__(*args, **kwargs)
print("New class instance created!")
return NewClass
@my_class_decorator
class MyClass:
def __init__(self, value):
self.value = value
my_obj = MyClass(10)
When you run the code, the output will be:
New class instance created!
Conclusion
Decorators are a powerful feature in Python that can greatly simplify the process of adding functionality to your code. They are widely used in many Python frameworks and libraries, and are a key part of the Python ecosystem.
For more information on decorators, you can read the official Python documentation or check out the Python Decorators Tutorial.