每次我运行此代码。 Tracker类在输入文本文件的每一个新行上创建一个新对象。我想在你第一次运行代码时只创建一个对象,并在整个输入文件中继续使用该对象,而不是每次调用我的类时都不创建新对象。
class Tracker(object):
def __init__(self,region):
self.region = region
def make_tracker(self):
self.region = re.search(r'CLI Command: \'show card detail\'',line)
if self.region:
print line
self.region = "CPM OR IOM"
return self.region
end = re.search(r'(SUN|MON|TUE|WED|THU|FRI|SAT)(.*)(\d)(\d)(\d)(\d) UTC:$',line)
if end:
flag = "end"
return flag
with open ('/home/thamer/SAMPLE.TXT','r') as f:
for line in f:
first = Tracker(line)
region = first.make_tracker()
if region =="CPM or IOM":
print "CPM or IOM"
答案 0 :(得分:3)
您应该将with
语句更改为以下内容:
with open ('/home/thamer/SAMPLE.TXT','r') as f:
tracker = Tracker("")
for line in f:
tracker.region = line
region = tracker.make_tracker()
if region =="CPM or IOM":
print "CPM or IOM"
这样,您每次都会更改tracker.region
而不是tracker
。