我可以在def __init__中添加方法吗?

时间:2016-01-22 18:23:05

标签: python python-2.7 class

使用python 2.7.6,我一直在尝试编写一个类,它可以从给定zip文件中的几个xml文件中提取xml数据片段。我希望能够在使用该类后以任何顺序使用任何方法,因此希望解压缩阶段在课堂后面。

这是我第一次真正尝试使用类,因为我对python很新,所以我正在学习。

我定义了将数据解压缩到内存并在其他方法中使用这些方法的方法 - 然后意识到使用多种方法时效率非常低。由于解压缩步骤对于类中的任何方法都是必需的,有没有办法将它构建到init定义中,所以它只在首次创建类时才执行一次?

我目前拥有的例子:

class XMLzip(object):
    def __init__(self, xzipfile):
        self.xzipfile = xzipfile

    def extract_xml1(self):
        #extract the xmlfile to a variable

    def extract_xml2(self):
        #extract xmlfile2 to a variable

    def do_stuff(self):
        self.extract_xml1()
        ....

    def do_domethingelse(self):
        self.extract_xml1()

有没有办法像我在下面展示的那样做?如果是这样,它叫什么 - 我的搜索效果不是很好。

class XMLzip(object):
    def __init__(self, xzipfile):
        self.xzipfile = xzipfile

        def extract_xml1()
            # extract it here

        def extract_xml2()
            # extract it here

    # Now carry on with normal methods
    def do_stuff(self):
        ...

2 个答案:

答案 0 :(得分:2)

您可以在初始化程序中调用您在班级中定义的任何方法。

演示:

>>> class Foo(object):
...    def __init__(self):
...        self.some_method()
...    def some_method(self):
...        print('hi')
... 
>>> f = Foo()
hi

我从你的问题中得出你只需要提取文件一次。保持您的课程原样,并使用__init__中的提取方法,并为提取的内容设置所需的属性/变量。

例如

def __init__(self, xzipfile):
    self.xzipfile = xzipfile
    self.extract1 = self.extract_xml1()
    self.extract2 = self.extract_xml2()

这当然要求你的提取方法有一个返回值,不要忘记。

答案 1 :(得分:2)

__init__你可以做任何你想做的事情来初始化你的课程,在这种情况下看起来像你需要的东西是这样的

class XMLzip(object):
    def __init__(self, xzipfile):
        self.xzipfile = xzipfile
        self.xml1 = #extract xml1 here
        self.xml2 = #extract xml2 here

    def do_stuff(self):
        ...

如果您只需要执行一次提取部分,则执行此操作并将结果保存在类实例中的其他属性中。

我怀疑提取过程非常相似,所以你可以把它变成你的类或外面的函数,这取决于你的偏好,并提供额外的参数来处理特异性,例如像这样的东西

外部版本

def extract_xml_from_zip(zip_file,this_xml):
    # extract the request xml file from the given zip_file
    return result

class XMLzip(object):
    def __init__(self, xzipfile):
        self.xzipfile = xzipfile
        self.xml1 = extract_xml_from_zip(xzipfile,"xml1")
        self.xml2 = extract_xml_from_zip(xzipfile,"xml2")

    def do_stuff(self):
        ...

内部版本

class XMLzip(object):
    def __init__(self, xzipfile):
        self.xzipfile = xzipfile
        self.xml1 = self.extract_xml_from_zip("xml1")
        self.xml2 = self.extract_xml_from_zip("xml2")

    def extract_xml_from_zip(self,this_xml):
        # extract the request xml file from the zip_file in self.xzipfile
        return result

    def do_stuff(self):
        ...