请考虑以下代码:
from weakref import ref
class Klass(object):
# __slots__ = ['foo']
def __init__(self):
self.foo = 'bar'
k = Klass()
r = ref(k)
当我取消注释__slots__
时,它能够正常工作。但在Python 2.6下会出现TypeError: "cannot create weak reference to 'Klass' object"
错误。
请问有人知道这是Python和__slots__
的固有限制还是一个bug?如何解决这个问题?
TypeError: cannot create weak reference to given object
。它发生在Python 2.7、3.5、3.6、3.7中,但有趣的是,在pypy和pypy3中却没有发生。 - Mikaelblomkvistsson