我们如何将属性从子节点传递给父节点?

时间:2015-03-18 17:22:10

标签: python python-2.7 oop

我正在尝试将列表从子级传递给父级。 在这里,我希望课程IVone92c应将其属性candidateList传递给IVone83c,它应该在自己的列表中得到相同的内容。而是将对象附加到IVone92c的candidateList中。为什么会这样?如何实现我想要的输出?

class IVone83c(Object):
    def __init__(self):
        self.candidateList = list()

    def resolve(self, SabxarUpa, candiList):
        self.candidateList.extend(candiList)


class IVone92c(IVone83c):

    def check(self,SabxarUpa, rule=None):
            self.candidateList = [IVone92]
             super(IVone92c, self).resolve(SabxarUpa, self.candidateList)

1 个答案:

答案 0 :(得分:1)

  

为什么会这样?

class IVone83c(object):
    def __init__(self):
        self.candidateList = ['goodbye']

    def resolve(self, SabxarUpa, candiList):
        print self.candidateList
        print self


class IVone92c(IVone83c):

    def check(self,SabxarUpa, rule=None):
        self.candidateList = [IVone92c]
        super(IVone92c, self).resolve(SabxarUpa, self.candidateList)

iv92 = IVone92c()
print iv92

--output:--
<__main__.IVone92c object at 0x2bdc30>  #<--Note the id
[<class '__main__.IVone92c'>]
<__main__.IVone92c object at 0x2bdc30>  #<--Note the id
  

超级(类型[,对象或类型])

     

返回一个代理对象,该方法将方法调用委托给父...

     

如果省略第二个参数,则返回的超级对象是   未结合的。

相反,如果提供了第二个参数,则超级对象绑定到第二个参数。 super()调用中的第二个参数是IVone92c_instance Bound 表示super()将IVone92c_instance作为父方法的第一个参数传递,这意味着IVone92c_instance被赋值给父方法中的self参数变量,意味着在父方法self中是IVone92c_instance

  

如何实现所需的输出?

目前尚不清楚您想要的输出是什么。你说:

  

这里我期待IVone92c类应该传递它的属性   候选列表到IVone83c

但当然,这没有任何意义。你想将一个列表传递给一个类?那是什么意思?你期望发生什么?正如评论中提到的jonrsharpe,您可以将数据存储在类属性中。那是你想要做的吗?

或者,您是否想要创建父类的实例,然后更新其列表,然后让父实例奇迹般地存活,直到您准备好检索它为止?

class IVone83c(object):
    def __init__(self):
        self.candidateList = ['goodbye']

    def resolve(self, SabxarUpa, candiList):
        #print(self.candidateList)
        print(self)
        self.candidateList.extend(candiList)


class IVone92c(IVone83c):

    def check(self,SabxarUpa, rule=None):
        self.candidateList = [IVone92c]
        iv83 = IVone83c()
        iv83.candidateList.extend(self.candidateList)
        self.candidateList = iv83.candidateList[:]
        print iv83.candidateList
        print self.candidateList
        #Where do you want to save iv83?

iv92 = IVone92c()
iv92.check('hello')

--output:--
['goodbye', <class '__main__.IVone92c'>]
['goodbye', <class '__main__.IVone92c'>]