gpt4 book ai didi

python - __slots__、_fields_ 和继承的交叉点出现异常

转载 作者:行者123 更新时间:2023-12-01 05:57:22 25 4
gpt4 key购买 nike

当我运行这个(2.7.3)时,我得到这个输出:

'Slotted1' object has no attribute 'c'
attribute c added to <class '__main__.Slotted2'>

我不明白 Slotted1 和 Slotted2 之间的行为差​​异。谁能解释一下吗?

from ctypes import *

class BracedStructure(Structure):
def __init__(self, **args):
super(BracedStructure,self).__init__(**args)

class Slotted1(Structure):
__slots__ = ['a','b']
_fields_ = [('a',c_int8),('b',c_int8)]
def __init__(self, **args):
super(Slotted1,self).__init__(**args)
def attemptToAddField(self):
self.c = '?'
print 'attribute c added to %s' % self.__class__

class Slotted2(BracedStructure):
__slots__ = ['a','b']
_fields_ = [('a',c_int8),('b',c_int8)]
def __init__(self, **args):
super(Slotted2,self).__init__(**args)
def attemptToAddField(self):
self.c = '?'
print 'attribute c added to %s' % self.__class__

if '__main__' == __name__:
s1 = Slotted1(a=1,b=2)
try:
s1.attemptToAddField()
except AttributeError as e:
print e

s2 = Slotted2(a=1,b=2)
try:
s2.attemptToAddField()
except AttributeError as e:
print e

最佳答案

看看这个:http://docs.python.org/reference/datamodel.html#slots

When inheriting from a class without __slots__, the __dict__ attribute of that class will always be accessible, so a __slots__ definition in the subclass is meaningless.

碰巧 BracedStructure 没有 __slots__,因此它覆盖了 Slotted2 中的 __slots__ 声明。

关于python - __slots__、_fields_ 和继承的交叉点出现异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11818711/

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