为什么python装饰程序会丢失func属性_udoc__;?
为什么结果是为什么python装饰程序会丢失func属性_udoc__;?,python,decorator,Python,Decorator,为什么结果是None?当我使用decorator时发生了什么?谢谢你的回答 这是因为您的装饰程序基本上正在替换您的函数。您需要使用来存储修饰后的函数内部,如\uuuu name\uuuuu和\uuuu doc\uuuu 通过向decorator函数添加docstringliving(),您可以轻松地测试这一点: 保存包装函数名称和docstring的文档示例 >>> def decor(fun): ... def living(*args, **kw): ...
None
?当我使用decorator时发生了什么?谢谢你的回答 这是因为您的装饰程序基本上正在替换您的函数。您需要使用来存储修饰后的函数内部,如\uuuu name\uuuuu
和\uuuu doc\uuuu
通过向decorator函数添加docstringliving()
,您可以轻松地测试这一点:
保存包装函数名称和docstring的文档示例
>>> def decor(fun):
... def living(*args, **kw):
... """This is the decorator for living()"""
... return fun(*args, **kw)
... return living
...
>>> @decor
... def test():
... """function doc"""
... pass
...
>>> test.__doc__
'This is the decorator for living()'
因为在装饰器中包装函数时:
>>> from functools import wraps
>>> def my_decorator(f):
... @wraps(f)
... def wrapper(*args, **kwds):
... print 'Calling decorated function'
... return f(*args, **kwds)
... return wrapper
...
>>> @my_decorator
... def example():
... """Docstring"""
... print 'Called example function'
...
>>> example()
Calling decorated function
Called example function
>>> example.__name__
'example'
>>> example.__doc__
'Docstring'
您将返回由装饰程序创建的函数(living
,在本例中),该函数没有相同的docstring等。它不会“丢失”这些数据,living
从未拥有过它
您可以通过以下方式解决此问题:
一个快速演示来证明这一点:
from functools import wraps
def decor(fun):
@wraps(fun)
def living(*args, **kw):
...
return func
对
>>> def wrapper(f):
def func(*args):
"""The wrapper func's docstring."""
return f(*args)
return func
>>> @wrapper
def test(x):
"""The test func's docstring."""
return x ** 2
>>> test.__doc__
"The wrapper func's docstring."
非常感谢。使用decorator时,当前运行的函数将变为(
living
,在本例中)并在其中运行test()。是吗?是的-没错-@decor
是test=decor(test)
from functools import wraps
def decor(fun):
@wraps(fun)
def living(*args, **kw):
...
return func
>>> def wrapper(f):
def func(*args):
"""The wrapper func's docstring."""
return f(*args)
return func
>>> @wrapper
def test(x):
"""The test func's docstring."""
return x ** 2
>>> test.__doc__
"The wrapper func's docstring."
>>> from functools import wraps
>>> def wrapper(f):
@wraps(f)
def func(*args):
"""The wrapper func's docstring."""
return f(*args)
return func
>>> @wrapper
def test(x):
"""The test func's docstring."""
return x ** 2
>>> test.__doc__
"The test func's docstring."