Python 3.6.5“多个库具有实例布局冲突".当具有__slot__的类具有多继承性时 [英] Python 3.6.5 "Multiple bases have instance lay-out conflict" when multi-inheritance of classes having __slots__

查看:88
本文介绍了Python 3.6.5“多个库具有实例布局冲突".当具有__slot__的类具有多继承性时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我运行此代码,则会收到主题错误消息.但为什么?以及如何避免它使C类具有其父级插槽?

If I run this code, I'v got the subject error message. But why? And how to avoid it getting the C class having its parents slots?

class A():
        __slots__ = ['slot1']

class B():
        __slots__ = ['slot2']

class C(A, B):
        __slots__ = []

推荐答案

简单地说,您做不到.

文档中所述,

可以使用具有多个带槽父类的多重继承,但是只允许一个父类具有由插槽创建的属性(其他基类必须具有空的插槽布局)-违反会引发TypeError.

Multiple inheritance with multiple slotted parent classes can be used, but only one parent is allowed to have attributes created by slots (the other bases must have empty slot layouts) - violations raise TypeError.

__slots__的想法是为实例的内存布局中的每个属性保留特定的插槽. AB试图为slot1slot2属性保留其内存布局的相同部分,并且C不能为两个属性保留相同的内存.只是不兼容.

The idea behind __slots__ is to reserve specific slots for each attribute in the memory layout of your instances. A and B are trying to reserve the same part of their memory layout for the slot1 and slot2 attributes, and C can't have the same memory reserved for two attributes. It's just not compatible.

感谢在注释中提及的JCode,以下方法已修改为正确.

但是总有办法,如果有多个继承的类,如果需要__slots__,我个人更喜欢使用包含所有必需插槽的通用基.

But there is always the way, I personally prefer to use a common base contained all required slots if __slots__ is necessary while there is multiple inherited class.

import pympler.asizeof
class base():
    __slots__ = ['a','b']

class A(base):
    __slots__ = []

class B(base):
    __slots__ = []

class C(A,B):
    __slots__ = []

class D():
    pass

#Update
bb = base()
bb.a = 100
bb.b = 100
print(pympler.asizeof.asizeof(bb))
a = A()
a.a = 100
a.b = 100
print(pympler.asizeof.asizeof(a))
c = C()
c.a = 100
c.b = 100
print(pympler.asizeof.asizeof(c))
d = D()
d.a = 100
d.b = 100
print(pympler.asizeof.asizeof(d))

更新 这4个值分别是88、88、88和312.尽管__slots__保留.

Update The 4 values will be 88, 88, 88, 312. Though __slots__ reserved.

这篇关于Python 3.6.5“多个库具有实例布局冲突".当具有__slot__的类具有多继承性时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆