1

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

2 回答 2

2

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

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

碰巧 BracedStructure 没有__slots__,因此它否决了__slots__中的声明Slotted2

于 2012-08-05T18:01:32.487 回答
0

那是因为继承Slotted2了. 所以它会接受新的论点,不管__dict__BracedStructure__slots__

于 2012-08-05T18:00:57.493 回答