Python - 难以调用父(ElementTree)类的方法

时间:2013-04-22 20:57:56

标签: python class inheritance parent-child elementtree

以下是我导入ElementTree的方法:

try:
    import xml.etree.cElementTree as ET
except ImportError:
    import xml.etree.ElementTree as ET

以下是我班级的片段:

class Foo(ET.ElementTree):
    def __init__(self, *args):
        if args[0] == "file":
            # populate from xml file
            self = load_xml(self, *args[1:])
        elif args[0] == "user_input":
            # populate from user_input
            self = load_from_user_input(self, *args[1:])
        else:
            raise ValueError("Error initializing Foo: Invalid argument")

    def save_xml(self, file_name):
        self.write(file_name + FOO_EXTENSION, xml_declaration=True, encoding='utf-8', method='xml')

init 和save_xml按预期工作。当事情变得混乱时,我需要在方法中使用Foo对象的根,例如将某些东西附加到Foo ElementTree的根目录:

root = self.getroot()
root.append(something)

这会产生此错误:

AttributeError: getroot
  • 如何在Foo中正确调用getroot()?

  • 为什么self.getroot()不起作用,但是self.write()呢?

  • 我是如何继承ElementTree的 宾语?

  • 我无意识地以面对面的方式进入一个重要的面向对象 概念障碍?

1 个答案:

答案 0 :(得分:0)

我不熟悉ET.ElementTree类,但它基本上就是这样的

class Base(object):
    def __init__(self,*args,**kwargs):
       print "Base Constructor Recieved:",args,kwargs
       pass #do something with the args and kwargs

    def do_something(self,*args):
       print "CALLED BASE DO SOMETHING!"

class InheritsFromBase(Base):
    def __init__(self,*args,**kwargs):
        #modify args and kwargs how you want
        new_args = ["a","b","v"]
        super(Base,self).__init__(*new_args,**kwargs) #initialize super class

    def do_something(self,operator,lhs,rhs):
        print "Do Something InheritsFromBase %s%s%s"%(lhs,operator,rhs)
        super(Base,self).do_something("arg1","arg2","arg3","...")

x = InheritsFromBase()
x.do_something("%",5,4)

如果基类没有从对象继承,您可能无法使用super语句,下面将介绍替代方法(只是init方法)

def __init__(self,*args,**kwargs):
    #modify args and kwargs how you want
    new_args = ["a","b","v"]
    Base.__init__(self,*new_args,**kwargs) #initialize super class

我怀疑这里的某个地方是你所缺少的。你可能需要以某种方式调用超级构造函数。