我试图在一个类中实例化多个对象。我试图在类中而不是main函数中实例化它们。我是python的新手,所以想学习。例如,我有这段代码,我的输入文件是一个包含所有字符串的文本文件。我想在区域中的正则表达式为真且/或子区域为真时实例化对象。我想在那里实例化它们而不是在main函数中。我怎样才能做到这一点?因为每次运行我的代码时,我都可以有零个或一个或两个对象:
class Tracker(object):
def __init__(self):
self.region = ""
self.subregion = ""
def updateRegion(self,input):
if self.endingRegion:
self.region = ""
if self.endingSubRegion:
self.subregion = ""
#Regions
temp = re.search(r'CLI Command: \'(.*)\'', input)
if temp:
self.region = temp.group(1)
print self.region
#SubRegions
temp = re.search(r'Equipped Type \(if different\)',input)
if temp:
self.subregion = "Equipped Type"
print self.subregion
def main():
with open ('/home/thamer/TS_ncren202_XRS-20_20150624_12.0.R6.txt','r') as f:
tracker = Tracker()
for line in f:
tracker.updateRegion(line)
region = tracker.getRegion()
subregion = tracker.getSubRegion()
if __name__ == '__main__':
main()