python __wrapped__
时间: 2023-10-18 15:04:34 浏览: 46
`__wrapped__` 是一个特殊的属性,可用于访问被装饰函数的原始函数对象。在装饰器中,当一个函数被其他函数包装时,`__wrapped__` 属性可以用于获取原始函数对象。
举个例子,考虑以下代码:
```python
def decorator(func):
def wrapper(*args, **kwargs):
print("Before function execution")
result = func(*args, **kwargs)
print("After function execution")
return result
return wrapper
@decorator
def my_function():
print("Inside my_function")
print(my_function.__wrapped__) # 访问被装饰的函数对象
```
在上面的代码中,`decorator` 是一个装饰器,它将一个函数包装在内部的 `wrapper` 函数中。通过访问 `my_function.__wrapped__`,我们可以获取原始的 `my_function` 函数对象,即被装饰前的函数。
注意:`__wrapped__` 属性仅在使用 `functools.wraps` 装饰器进行装饰时才可用。这个装饰器会确保原始函数的属性和文档字符串等信息在被包装函数中得以保留。
相关问题
__wrapped__使用方法
`__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` 函数对象,没有被装饰器包裹。
C:\Users\GW00321286\.conda\envs\python_39\python.exe E:\code-study\coda\test.py Traceback (most recent call last): File "E:\code-study\coda\test.py", line 13, in <module> c = gpd.GeoSeries(hits) File "C:\Users\GW00321286\.conda\envs\python_39\lib\site-packages\geopandas\geoseries.py", line 208, in __init__ s = pd.Series(data, index=index, name=name, **kwargs) File "C:\Users\GW00321286\.conda\envs\python_39\lib\site-packages\pandas\core\series.py", line 454, in __init__ data = com.maybe_iterable_to_list(data) File "C:\Users\GW00321286\.conda\envs\python_39\lib\site-packages\pandas\core\common.py", line 308, in maybe_iterable_to_list return list(obj) File "C:\Users\GW00321286\.conda\envs\python_39\lib\site-packages\shapely\prepared.py", line 32, in contains return self.context.contains(other) File "C:\Users\GW00321286\.conda\envs\python_39\lib\site-packages\shapely\geometry\base.py", line 658, in contains return _maybe_unpack(shapely.contains(self, other)) File "C:\Users\GW00321286\.conda\envs\python_39\lib\site-packages\shapely\decorators.py", line 77, in wrapped return func(*args, **kwargs) File "C:\Users\GW00321286\.conda\envs\python_39\lib\site-packages\shapely\predicates.py", line 540, in contains return lib.contains(a, b, **kwargs) TypeError: One of the arguments is of incorrect type. Please provide only Geometry objects.
根据你提供的信息,这是一个 Python 报错信息,其中指出了发生错误的位置在 test.py 文件的第 13 行。错误是由于在 GeoPandas 库的 GeoSeries 对象中传入了错误的参数类型导致的。具体来说,错误信息指出传入了一个非几何对象作为参数,而 GeoSeries 对象只能接受几何对象作为参数。建议检查代码,确保在 GeoSeries 对象中只传入几何对象。