__wrapped__使用方法
时间: 2023-07-21 10:27:24 浏览: 154
`__wrapped__()` 是 Python 3.2 引入的一个函数属性,它用于获取被装饰后的函数的原始函数对象。在使用装饰器时,装饰器会将原始函数包裹在一个新的函数中,如果需要获取原始函数对象,就可以使用 `__wrapped__()` 方法。
例如,有一个装饰器 `my_decorator`:
```python
def my_decorator(func):
def wrapper(*args, **kwargs):
print("Before the function is called.")
result = func(*args, **kwargs)
print("After the function is called.")
return result
return wrapper
```
使用 `my_decorator` 装饰一个函数 `my_function`:
```python
@my_decorator
def my_function():
print("The function is called.")
```
此时,`my_function` 已经被 `my_decorator` 装饰过,如果需要获取原始函数对象,可以通过 `__wrapped__()` 方法来获取:
```python
my_function.__wrapped__()
```
执行结果为:
```
The function is called.
```
可以看到,使用 `__wrapped__()` 方法获取的是原始的 `my_function` 函数对象,没有被装饰器包裹。
阅读全文
相关推荐
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)