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.
class SlotBase(type):
def __new__(cls,name,bases,dctn):
if ('_slots_' in dctn) and not ('__slots__' in dctn):
dctn['__slots__'] = []
elif '__slots__' in dctn:
for base in bases:
if hasattr(base,'_slots_'):
dctn['__slots__'] += getattr(base,'_slots_')
return super().__new__(cls,name,bases,dctn)
然后在基类上部署。在
^{pr2}$
如果我们执行以下代码
c=C()
c.classPropertyC
c.classPropertyA
c.functA()
c.functB()
c.slot1='Slot exists then assignment is accepted'
c.slot3='Slot does not exists then assignment couldn\'t be accepted'
这将产生以下输出
Just another silly value
Some silly value
I'm functA
I'm functB
Traceback (most recent call last):
File "/tmp/slots.py", line 41, in <module>
c.slot3='Slot does not exists then assignment couldn\'t be accepted'
AttributeError: 'C' object has no attribute 'slot3'
简单地说,你就是做不到。在
如Documentation所述
__slots__
背后的思想是为实例的内存布局中的每个属性保留特定的插槽。^这两个感谢注释中所述的JCode,以下方法已修改为正确。
但是总有办法,如果
__slots__
是必需的,而有多个继承类,我个人更喜欢使用包含所有必需插槽的公共基。在更新 这4个值将是88、88、88、312。尽管
__slots__
保留。在在我看来,这是一个愚蠢的变通办法。 这就是为什么当
__slots__
为空时不会引发TypeError
,而拥有一个空的__slots__
属性会保留python的“奇怪”行为,即在分配给__slots__
中未定义的属性时会发出警告。在因此,考虑以下元类:
然后在基类上部署。在
^{pr2}$如果我们执行以下代码
这将产生以下输出
相关问题 更多 >
编程相关推荐