我在尝试使用修饰符更新函数的包装器时遇到了一个相当隐晦的错误消息(至少对我来说是这样)。有什么办法补救吗?在
我试着使我的代码尽可能通用,这样它也适用于其他情况。在
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__'
decorator将一个函数作为参数并返回另一个“decorated”函数。您正在传递一个字符串并试图返回一个实际上是函数工厂的函数。}需要一个函数。函数对象具有
functools.wraps
和{__module__
属性,而str
的实例没有__module__
属性。在是否要从字符串“x**2”生成函数?在
您的
decorator
的实现是不必要的。只需使用functools.wraps
:但是,在本例中,您不需要decorator,而是需要一个函数工厂。在
^{pr2}$现在可以这样使用:
警告:外科医生已经确定
eval
对你的健康有害相关问题 更多 >
编程相关推荐