python - 定义全局变量的问题

标签 python python-2.7 global-variables

我正在编写一个类,它读取文件中“结束”行之前的行数

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/

相关文章:

python - 在主脚本中保留 helper python 脚本的环境

python - 大字符串的某些部分不会被 str.replace() 函数替换

python - 如何将字符添加到正则表达式匹配字符串的开头?

linux - Python : Import cairo error (2. 7 & 3.6) undefined symbol :cairo_tee_surface_index

google-apps-script - 如何在 Google Apps 脚本中定义全局变量

java - 我怎样才能让全局有一个唯一的号码?

python - python 'import' 可以扩展到 zip 以外的其他存档类型吗?

python - 向字符串填充空格或零

python - Flask 渲染模板未显示解析为 html 页面的消息?

javascript - 如何在 Meteor 中的服务器和客户端代码之间共享一个全局变量