__slots __,_ fields_和继承的交集处的异常

时间:2012-08-05 17:55:01

标签: python inheritance field slots

当我运行这个(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

2 个答案:

答案 0 :(得分:2)

检查出来:http://docs.python.org/reference/datamodel.html#slots

  

从没有__slots__的类继承时,该类的__dict__属性将始终可访问,因此子类中的__slots__定义毫无意义。

BracedStructure没有__slots__,因此它取代了__slots__中的Slotted2声明。

答案 1 :(得分:0)

这是因为Slotted2继承了__dict__的{​​{1}}属性。因此无论BracedStructure

如何,它都会接受新的参数
相关问题