Python 装饰器英文
时间: 2024-06-16 21:02:14 浏览: 16
In Python, a decorator is a special type of function that allows you to modify or enhance the behavior of another function or class without changing its source code. Decorators are often used for tasks like adding logging, time tracking, caching, or authentication to a piece of functionality. They follow a simple pattern where a decorator takes in a function or class as an argument and returns a new version of that function or class with the desired modifications.
The syntax for using a decorator typically involves placing it before the function or class definition, followed by an `@decorator_name` statement. Here's a basic example:
```python
# Define the decorator function
def my_decorator(func):
def wrapper():
print("Something is happening before the function call.")
func()
print("Something is happening after the function call.")
return wrapper
# Apply the decorator to a function
@my_decorator
def say_hello():
print("Hello!")
# Now, when you call say_hello, it runs through the decorated function
say_hello()
```