我正在编写一个类,它读取文件中“结束”行之前的行数
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,所以如果有任何风格上的差异,我深表歉意
最佳答案
您可以在创建它们的函数之外的函数中使用全局变量“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
'''
关于python - 定义全局变量的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20823547/