在尝试使用装饰器更新函数的包装器时,我遇到了一个相当神秘的(至少对我而言)错误消息。有什么想法可以解决这个问题吗?
我试图使我的代码尽可能通用,以便它也适用于其他情况。
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__
期望的输出:
>>>x**2
实际输出:
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__'