问题
I'm confused about the namespace and scope of variables in python
Suppose I have a test.py:
# -*- coding: utf-8 -*-
"""
@author: jason
"""
if __name__ == '__main__':
global strName
print strName
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]:
I was wondering why this happens and is there any way to access strName in test.py?
回答1:
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.
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
other code that wants to use test.py:
import test
test.print_thing("Joe")
回答2:
test.py:
strName = "John Doe"
print strName
Interactive Shell:
$ python
>>> from test import strName
>>> print strName
John Doe
回答3:
Global is specifically for cases where you have a variable defined outside a method, and want to use it inside that method without passing in parameters. It is put at the top of the method so that python treats that variable as a global variable, rather then a new local variable with the same name. Global is not a way to declare variables, and since strName isn't in existance, global can't figure out where the location of strName is.
来源:https://stackoverflow.com/questions/24075140/how-to-access-global-variable-within-main-scope