I'm learning Python coming from a good background with other languages. My question is mostly academic, as I know that what I'm asking is seldom needed and is definitely not a good programming practice.
我正在学习Python与其他语言的良好背景。我的问题主要是学术性的,因为我知道我所要求的内容很少需要,绝对不是一个好的编程实践。
Here is what I'm asking:
这就是我要问的问题:
x = 'global scope' # global
def func():
x = 'local scope' # global x is now shadowed
print(global x) # is this somehow possible?
Attempt #1
def attempt1():
x = 'local scope' # shadowded
global x
print(x) # error
This results in an error: name 'x' is assigned to before global declaration.
这会导致错误:在全局声明之前将名称“x”分配给它。
Attempt #2
def attempt2():
x = 'local scope' # shadowded
print(__main__.x) # error: __main__ not defined
The Python documentation on namespaces states suggest that #2 (or something like it) should be possible. See Python Tutorial 9.2
关于命名空间状态的Python文档表明#2(或类似的东西)应该是可能的。请参阅Python教程9.2
"The statements executed by the top-level invocation of the interpreter, either read from a script file or interactively, are considered part of a module called __main__, so they have their own global namespace."
“从脚本文件中读取或交互式地从顶层调用解释器执行的语句被认为是名为__main__的模块的一部分,因此它们具有自己的全局命名空间。”
However attempting to access __main__
from either a script or the console results in an error. Also, the global attribute __name__
refers to the outermost module as __builtins__
, but this only contains the built-in variables, not any user defined global ones. If the variable were delcared in an outside module, one that had been imported, it could be accessed with __module_name__.variable
.
但是,尝试从脚本或控制台访问__main__会导致错误。此外,全局属性__name__将最外层模块称为__builtins__,但这仅包含内置变量,而不包含任何用户定义的全局变量。如果变量在外部模块(已导入的模块)中进行了delcared,则可以使用__module_name __。variable访问它。
3 个解决方案
#1
7
try globals():
x = 'global scope' # global
def func():
x = 'local scope' # global x is now shadowed
print(globals()['x']) # is this somehow possible?
func()
#2
6
You can use globals()['x']
. However, you're better off just giving your local variable a different name so you can just do global x
to do whatever you need to do with the global variable.
你可以使用globals()['x']。但是,你最好只给你的局部变量一个不同的名字,这样你就可以做全局x来做你需要做的全局变量。
#3
4
globals()
returns a dictionary of the current global variables. You can print globals()['x']
.
globals()返回当前全局变量的字典。你可以打印globals()['x']。
#1
7
try globals():
x = 'global scope' # global
def func():
x = 'local scope' # global x is now shadowed
print(globals()['x']) # is this somehow possible?
func()
#2
6
You can use globals()['x']
. However, you're better off just giving your local variable a different name so you can just do global x
to do whatever you need to do with the global variable.
你可以使用globals()['x']。但是,你最好只给你的局部变量一个不同的名字,这样你就可以做全局x来做你需要做的全局变量。
#3
4
globals()
returns a dictionary of the current global variables. You can print globals()['x']
.
globals()返回当前全局变量的字典。你可以打印globals()['x']。