zii*_*ima 3 python inheritance weak-references
我试图在类上使用弱引用,在这些类上我使用插槽来节省一些内存,但无法创建派生类。
class A(object):
__slots__ = ['__weakref__']
class B(A):
__slots__ = A.__slots__ + ['foo']
#TypeError: Error when calling the metaclass bases
# __weakref__ slot disallowed: either we already got one, or __itemsize__ != 0
Run Code Online (Sandbox Code Playgroud)
诀窍在哪里?我没有找到任何解决方案。我正在使用python 2.7.3。
在派生类中,你应该不放在基类中定义的插槽。
实际上,错误提示:
TypeError:__weakref__不允许在调用元类基础插槽时出错 :我们已经有一个,或者__itemsize__ != 0
只需使用:
class B(A):
__slots__ = ['foo']
Run Code Online (Sandbox Code Playgroud)
在文档中对此进行了解释__slots__:
__slots__声明的动作仅限于定义它的类。结果,子类将具有一个,__dict__除非它们也进行了定义__slots__(该子类只能包含任何其他 插槽的名称)。
| 归档时间: |
|
| 查看次数: |
517 次 |
| 最近记录: |