gpt4 book ai didi

python - 弱引用和 __slots__

转载 作者:IT老高 更新时间:2023-10-28 21:01:10 24 4
gpt4 key购买 nike

考虑以下代码:

from weakref import ref

class Klass(object):
# __slots__ = ['foo']
def __init__(self):
self.foo = 'bar'

k = Klass()
r = ref(k)

它可以工作,但是当我取消注释 __slots__ 时,它会因 TypeError: "cannot create weak reference to 'Klass' object" 在 Python 2.6 下中断。

请问,有谁知道这是 Python 和 __slots__ 的固有限制还是错误?如何解决?

最佳答案

Without a __weakref__ variable for each instance, classes defining __slots__ do not support weak references to its instances. If weak reference support is needed, then add __weakref__ to the sequence of strings in the __slots__ declaration.

来自 Python documentation .

如果您将 __weakref__ 添加到 __slots__,您的代码将起作用:

>>> from weakref import ref
>>>
>>> class Klass(object):
>>> __slots__ = ['foo', '__weakref__']
>>> def __init__(self):
>>> self.foo = 'bar'
>>> k = Klass()
>>> k
=> <__main__.Klass object at ...>
>>> r = ref(k)
>>> r
=> <weakref at ...; to 'Klass' at ...>

关于python - 弱引用和 __slots__,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19526340/

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