使用python 2.7.6,我一直在尝试编写一个类,可以从给定的zip文件中的几个xml文件中提取xml数据片段。我希望能够按照任何顺序使用任何一种方法,因此我希望解压缩舞台能够在课堂上幕后。我可以在def __init__中添加方法吗?
这是我第一次真正尝试真正使用一个类,因为我对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):
...
是的,这是可能的吗?什么是问题?为什么不在'__init__'中使用提取方法而不是在那里定义它们? – timgeb
这是怎么做的?我从来没有在一个例子中看到它。它有名字吗?它可以帮助我搜索一个。 – emmalg
你的意思是像我现在那样定义提取方法,但是在init部分调用它们?这是如何工作的? – emmalg