def test(function):
def wrapper():
print("start")
function()
print("end")
return wrapper
@test
def hello():
print("hello")
hello()
This code snippet is an example of a Python decorator in action. Decorators are a powerful and expressive feature of Python that allows you to modify the behavior of functions or methods. Here's a breakdown of how this particular code works:
### The `test` Decorator
- **Definition**: The `test` function is defined as a decorator. It takes another function (`function`) as its argument. This pattern is typical for decorators, which are meant to "wrap" another function, potentially altering its behavior or augmenting it in some way.
- **The `wrapper` Function**: Inside `test`, a nested function named `wrapper` is defined. This function represents the new function that will replace the original `function` when the decorator is applied. The `wrapper` function adds behavior both before and after calling the original `function` — specifically, it prints "start" before calling `function` and "end" after.
- **Returning the `wrapper`**: The `wrapper` function is returned by the `test` decorator. This is crucial; it means that when you apply `@test` to a function, what you're really doing is replacing that function with the `wrapper` function.
### Applying the `test` Decorator
- **The `@test` Syntax**: The `@test` line above the definition of `hello` is syntactic sugar for `hello = test(hello)`. It applies the `test` decorator to the `hello` function. As a result, when you call `hello()`, you're actually calling `wrapper()`.
- **The `hello` Function**: This is a simple function that prints "hello". However, because it's decorated with `@test`, its behavior is augmented by the additional logic in the `wrapper` function defined inside `test`.
### Execution Flow
1. When you call `hello()`, you're actually calling the `wrapper` function returned by the `test` decorator.
2. "start" is printed.
3. The original `hello` function is called, printing "hello".
4. "end" is printed.
### Output
Thus, the output of calling `hello()` is:
```
start
hello
end
```
### Conclusion
This example demonstrates how decorators can be used to augment the behavior of functions in Python, adding functionality before and/or after the original function's execution without modifying the function's own code. Decorators are widely used in Python for logging, access control, memoization, and more.
'개념 > 혼자 공부하는 파이썬' 카테고리의 다른 글
python) size comparison function (2) | 2024.10.28 |
---|---|
python) Declare a function inside a class (0) | 2024.10.27 |
python) class parameter (0) | 2024.10.26 |
python) class function (1) | 2024.10.25 |
python) Passing function parameters to a function (1) | 2024.10.23 |