[英]Global variable not recognized in Python
What I have tried: 我尝试过的
def mnuRead(self, event):
global fn
dialog = wx.FileDialog(None, "Choose a file", os.getcwd(), "", "*.*", wx.OPEN)
if dialog.ShowModal() == wx.ID_OK:
countrylist = []
fn = dialog.GetPath()
fh = open(fn, "r")
csv_fh = csv.reader(fh)
for row in csv_fh:
countrylist.append(row)
fh.close()
for rows in countrylist:
self.myListCtrl.Append(rows)
def btnHDI(self, event):
myfile = open(fn, "rb")
In my first function, I prompt the user to open a file of their choice. 在我的第一个功能中,我提示用户打开他们选择的文件。 I have a declared, and then assigned a global variable to "fn". 我有一个声明,然后将全局变量分配给“ fn”。
When I call on "fn" in my btnHDI function, Python is saying that fn is "undefined". 当我在btnHDI函数中调用“ fn”时,Python表示fn是“未定义的”。
What am I doing wrong? 我究竟做错了什么? Is this not the proper use of a global variable? 这不是对全局变量的正确使用吗? How can I use the file path selected by the user in my "mnuRead" function in all my other functions? 在所有其他功能中,如何使用用户在“ mnuRead”功能中选择的文件路径?
If you insist on having fn
as a global, why not just have fn
defined in the module: 如果您坚持将fn
为全局fn
,为什么不在模块中定义fn
:
# Somewhere in the same .py module
fn = None
def mnuRead(self, event):
# Modify fn
def btnHDI(self, event):
# Read fn
You need to put fn
both out and in the function 您需要同时在函数中放入fn
fn = 2
def func():
global fn
You can read a global within a function but you cannot change it; 您可以在函数中读取全局变量,但不能更改它; python will automatically make it local unless you use global in front of the variable when you try and change it in the function. 除非您尝试在函数中更改变量,否则python会自动将其设置为局部变量,除非您在变量前面使用global。
Better to: 更好地:
fn = func():
return value to fn
unless you absolutely need it 除非你绝对需要
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.