gpt4 book ai didi

python-2.7 - functools.wrapper - AttributeError : attribute '__doc__' of 'type' objects is not writable

转载 作者:行者123 更新时间:2023-12-01 01:57:50 25 4
gpt4 key购买 nike

在执行下面的代码时,我得到 AttributeError: attribute '__doc__' of 'type' objects is not writable .

from functools import wraps

def memoize(f):
""" Memoization decorator for functions taking one or more arguments.
Saves repeated api calls for a given value, by caching it.
"""
@wraps(f)
class memodict(dict):
"""memodict"""
def __init__(self, f):
self.f = f
def __call__(self, *args):
return self[args]
def __missing__(self, key):
ret = self[key] = self.f(*key)
return ret
return memodict(f)

@memoize
def a():
"""blah"""
pass

追溯:

AttributeError Traceback (most recent call last)
<ipython-input-37-2afb130b1dd6> in <module>()
17 return ret
18 return memodict(f)
---> 19 @memoize
20 def a():
21 """blah"""

<ipython-input-37-2afb130b1dd6> in memoize(f)
7 """
8 @wraps(f)
----> 9 class memodict(dict):
10 """memodict"""
11 def __init__(self, f):

/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/functools.pyc in update_wrapper(wrapper, wrapped, assigned, updated)
31 """
32 for attr in assigned:
---> 33 setattr(wrapper, attr, getattr(wrapped, attr))
34 for attr in updated:
35 getattr(wrapper, attr).update(getattr(wrapped, attr, {}))

AttributeError: attribute '__doc__' of 'type' objects is not writable

即使提供了文档字符串,我也不知道这有什么问题。

如果没有包装它工作正常,但我需要这样做。

最佳答案

@wraps(f)主要设计为用作函数装饰器,而不是用作类装饰器,因此将其用作后者可能会导致偶尔出现奇怪的怪癖。

您收到的特定错误消息与 Python 2 上的内置类型限制有关:

>>> class C(object): pass
...
>>> C.__doc__ = "Not allowed"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: attribute '__doc__' of 'type' objects is not writable

如果你使用 Python 3,切换到 Python 2 中的经典类(通过继承 UserDict.UserDict 而不是 dict 内置),或者使用闭包来管理结果缓存而不是类实例,装饰器将能够从底层函数复制文档字符串。

关于python-2.7 - functools.wrapper - AttributeError : attribute '__doc__' of 'type' objects is not writable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39010366/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com