问题描述
我对python中变量的名称空间和范围感到困惑
I'm confused about the namespace and scope of variables in python
假设我有一个test.py:
Suppose I have a test.py:
# -*- coding: utf-8 -*-
"""
@author: jason
"""
if __name__ == '__main__':
global strName
print strName
然后,我定义一个名为strName的变量,并尝试在test.py中访问它,但是它会引发错误:
and then, I define a variable named strName and try to access it in the test.py, but it throws an error:
In [9]: strName = "Joe"
In [10]: run test.py hello
--------------------------------------------------------------------------- NameError Traceback (most recent call last) C:\Anaconda\lib\site-packages\IPython\utils\py3compat.pyc in execfile(fname, glob, loc)
195 else:
196 filename = fname
--> 197 exec compile(scripttext, filename, 'exec') in glob, loc
198 else:
199 def execfile(fname, *where):
d:\playground\test.py in <module>()
13 print "hello"
14 global strName
---> 15 print strName
16
NameError: global name 'strName' is not defined
In [11]:
我想知道为什么会这样,并且有什么方法可以访问test.py中的strName吗?
I was wondering why this happens and is there any way to access strName in test.py?
推荐答案
global
不是全局的. global
是模块级别的; min
和int
等真正的全局变量位于__builtin__
模块中(在Python 3中为builtins
).在模块级别使用global
声明是多余的.
global
isn't global. global
is module-level; truly global variables like min
and int
live in the __builtin__
module (builtins
in Python 3). Using a global
declaration at module level is redundant.
我强烈建议您通过另一种方式将数据传递到test.py
,例如在其中定义一个函数并将字符串作为参数传递:
I strongly recommend you pass your data to test.py
another way, such as by defining a function in there and passing your string as an argument:
test.py:
def print_thing(thing):
print thing
其他要使用test.py的代码:
other code that wants to use test.py:
import test
test.print_thing("Joe")
这篇关于如何访问__main__范围内的全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!