Python类继承(多个):为什么属性为空?即做对

时间:2012-09-22 13:04:40

标签: python class inheritance mixins

我尝试创建一个中间对象与其他地方一起工作,我可以将其传递给sqlalchemy模型进行创建:

从:

开始
class IntermediateObj(object):

    def __init__(self, raw):
        self.raw = raw
        self.sections = []
        self.fields = []
        self.elements = []
        super(IntermediateObj, self).__init__()

    def recurse(self, items):
        for k,v in items.iteritems():
            if isinstance(v, list):
                getattr(self, k).append(v)
                [self.recurse(i) for i in v]
            else:
                setattr(self, k, v)

传递给:

class MyClass(IntermediateObj, Base):

    def __init__:(self, attribute=None):
         self.attribute = attribute 
         super(MyClass, self).__init__

e.g。

ii = IntermediateObj(raw={'large':'nested_dictionary', sections=[{}, {}, {}]})
ii.recurse(ii.raw) #any help smoothing this bit over appreciated as well, but another question...
tada = MyClass(ii)

tada.sections
---> [] /// this should not be, it should correspond to ii.sections

在不应该的地方是空的,所以我还没有完全掌握继承。这必须是一个常见的问题,但我现在还没有发现任何我能理解的东西,只是在各种战术中徘徊。正确执行python类继承的任何输入。

1 个答案:

答案 0 :(得分:0)

class IntermediateObj(object):

    def __init__(self, raw):
        self.raw = raw
        self.sections = []
        self.fields = []
        self.elements = []

    def recurse(self, items):
        # this works ok, but passing the same arguments to the recurse function
        # which were passed to the constructor as well ,and then stored as a class
        # attribute, why, seems like self.raw is not even needed?
        for k,v in items.iteritems():
            if isinstance(v, list):
                getattr(self, k).append(v)
                [self.recurse(i) for i in v]
            else:
                setattr(self, k, v)


class MyClass(IntermediateObj):

    def __init__(self, attribute=None):  
        self.attribute = attribute
        super(MyClass, self).__init__(attribute)


ii = IntermediateObj({'large': 'nested_dictionary',
                      'sections': [{}, {}, {}]
                    })
ii.recurse(ii.raw)
print ii.raw
print ii.sections

# passing an instance of IntermediateObj is not the same as passing a dict (logically)
# yet the constructor of MyClass just forwards that instance object to the
# baseclasses constructor, while you initially passed a dict to the IntermediateObj
# constructor. 
tada = MyClass(ii)
# MyClass inherits the recurse method, but it won't magically be executed unless
# you call it, so just instantiating MyClass won't copy those values recursively
tada.recurse(ii.raw)
# now tada, it copied everything, and notice, I called recurse with ii.raw, which is the
# source dictionary, but I'm not even sure if you wanted it that way, it's not clear
# define your question more precisely
print tada.sections

我看到你已经接受了这个作为最好的答案,我觉得它很糟糕因为它没有得到真正的回答,所以我做了一个更新,就像我们在评论中所描述的那样,现在当MyClass的一个实例收到一个IntermediateObj的实例时,它将使用传递对象的原始参数调用基类的构造函数。在IntermediateObj的构造函数中也会调用recurse,因此它将在实例化时复制值:

class IntermediateObj(object):

    def __init__(self, raw):
        self.raw = raw
        self.sections = []
        self.fields = []
        self.elements = []
        self.recurse(raw)

    def recurse(self, items):
        for k,v in items.iteritems():
            if isinstance(v, list):
                getattr(self, k).append(v)
                [self.recurse(i) for i in v]
            else:
                setattr(self, k, v)


class MyClass(IntermediateObj):

    def __init__(self, intermediate_instance):  
        super(MyClass, self).__init__(intermediate_instance.raw)


ii = IntermediateObj({'large': 'nested_dictionary',
                      'sections': [{}, {}, {}]
                    })
print ii.raw
print ii.sections
tada = MyClass(ii)
print tada.sections
print tada.raw