使用与局部变量相同的名称修改全局变量 [英] Modifying global variable with same name as local variable
问题描述
假设我有一个全局变量 a
。在一个函数定义中,我们也有一个名为 a
的局部变量。有没有办法将全局变量的值赋给局部变量的值?
a ='foo'
def my_func(a ='bar'):
#如何设置全局a为本地值?
使用内置函数 globals()
。
>globals()
返回一个表示当前全局符号
表的字典。这总是当前模块的字典(在
函数或方法中,这是它定义的模块,而不是它被调用的
模块)。
a ='foo'
def my_func(a ='bar' ):
globals()['a'] = a
顺便说一句。值得一提的是,全球只是一个模块范围内的全球。
Suppose I have a global variable a
. And within a function definition, we also have a local variable named a
. Is there any way to assign the value of the global variable to that of the local variable?
a = 'foo'
def my_func(a = 'bar'):
# how to set global a to value of the local a?
Use build in function globals()
.
globals()
Return a dictionary representing the current global symbol table. This is always the dictionary of the current module (inside a function or method, this is the module where it is defined, not the module from which it is called).
a = 'foo'
def my_func(a = 'bar'):
globals()['a'] = a
BTW. it's worth mentioning, that the global is only "global" within scope of a module.
这篇关于使用与局部变量相同的名称修改全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!