我正在编写一个类,它在“end”行之前读取文件中的行数
class readFile:
global count
global txt
def __init__(self):
self.count = 0
def open(self,file):
self.txt = open(file,"r")
def cnt(self):
str = txt.readline()
while str != "end":
self.count += 1
str = txt.readline()
def printline(self):
print "the number of lines = %d" % count
obj = readFile()
obj.open(raw_input("which file do you want to read? \n"))
obj.cnt()
obj.printline()
但是当我运行这段代码时,我得到以下错误 - NameError:未定义全局名称'txt'
我正在从java转向python,所以如果有任何风格差异,我道歉
答案 0 :(得分:3)
你 可以 在除了创建它们的函数之外的函数中使用全局变量“by declaring it as global
in each function that assigns to it.”
但是,在这种情况下,txt
只需要成为该类的成员。
下面的评论,以帮助您从Java到Python的旅程......
#!/usr/bin/env python
class ReadFile(object): # Classes have titlecase names and inherit from object
def __init__(self):
self.count = 0
self.txt = None # Initialise the class member here
def open(self, filename): # file is a Python built-in. Prefer 'filename'
self.txt = open(filename, "r")
def cnt(self):
line = self.txt.readline() # str is a Python built-in. Prefer 'line'.
# Reference the class member with 'self.'
line = line.strip() # Remove any trailing whitespace
while line != "end": # TODO: What happens if this line doesn't appear?
self.count += 1
line = self.txt.readline().strip()
def printline(self):
print "the number of lines = %d" % self.count
obj = ReadFile()
obj.open(raw_input("which file do you want to read? \n").strip())
obj.cnt()
obj.printline()
'''
end
'''
答案 1 :(得分:1)
您的txt
不一定是全局变量。
在您的cnt函数中,只需使用self.txt
调用它即可。
对于您的打印行功能,请使用count
self.count
另一个提示:不要忘记关闭文件。
答案 2 :(得分:1)
请勿使用全局变量。
class readFile:
def __init__(self):
self.count = 0
def open(self,file):
self.txt = open(file,"r")
def cnt(self):
str = self.txt.readline()
while str != "end":
self.count += 1
str = self.txt.readline()
def printline(self):
print "the number of lines = %d" % self.count
答案 3 :(得分:0)
我知道你想要使用类,但如果它只计算文件中的行数,你也可以尝试这样的事情:
with open('test.py') as f:
l = [x.strip() for x in f.readlines()]
try: # assuming 'end' is the only word in the line
print 'the number of lines = {}'.format(len(l[:l.index('end')]))
except:
print 'string "end" not found'