使用decorator更新wrapp时遇到错误

2024-05-12 13:11:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我在尝试使用修饰符更新函数的包装器时遇到了一个相当隐晦的错误消息(至少对我来说是这样)。有什么办法补救吗?在

我试着使我的代码尽可能通用,这样它也适用于其他情况。在

def decorator(d):
    """Make function d a decorator: d wraps a function fn."""

    def _d(fn):
        return functools.update_wrapper(d(fn), fn)
    functools.update_wrapper(_d, d)
    return _d


@decorator
def f(fn):
    """Converts the string fn to a function and returns it.
    Because of the @decorator decorator, _f.__name__ should
    be identical to f.__name__"""

    f.__name__ = fn
    def _f(fn):
        return eval(fn)
    return _f

g = f('x**2')
print g.__name__

期望输出:

^{pr2}$

实际产量:

Traceback (most recent call last):
  File "C:\python\swampy-2.0\testcode.py", line 18, in <module>
    g = f('x**2')
  File "C:\python\swampy-2.0\testcode.py", line 6, in _d
    return functools.update_wrapper(d(fn), fn)
  File "C:\Python27\lib\functools.py", line 33, in update_wrapper
    setattr(wrapper, attr, getattr(wrapped, attr))
AttributeError: 'str' object has no attribute '__module__'

Tags: thetonameinpyreturndefline
1条回答
网友
1楼 · 发布于 2024-05-12 13:11:09

decorator将一个函数作为参数并返回另一个“decorated”函数。您正在传递一个字符串并试图返回一个实际上是函数工厂的函数。functools.wraps和{}需要一个函数。函数对象具有__module__属性,而str的实例没有__module__属性。在

是否要从字符串“x**2”生成函数?在

您的decorator的实现是不必要的。只需使用functools.wraps

def f(fn):
    """Converts the string fn to a function and returns it."""
    @functools.wraps(fn)
    def _f(fn):
        return eval(fn)
    return _f

但是,在本例中,您不需要decorator,而是需要一个函数工厂。在

^{pr2}$

现在可以这样使用:

>>> x_squared = factory("x**2")
>>> x_squared(x=7)
49

警告:外科医生已经确定eval对你的健康有害

相关问题 更多 >