我是 python 新手,我们如何引用与本地变量同名的全局变量。
spam = 'global spam'
def scope_test():
spam = 'local spam'
print(spam)
# access global spam and print or assign to the local spam
# print(global.spam)
# local.spam = global.spam (something like this)
scope_test()
请您参考如下方法:
这是不推荐的,如果你好奇问/做,我只是为了回答:
Python 3.5.2
>>> spam = 'global spam'
>>> def scope_test():
.. spam = 'local spam'
.. print(spam)
.. # access global spam and print or assign to the local spam
.. print(globals()['spam'])
.. spam = globals()['spam']
.. print(spam)
..
>>> scope_test()
输出:
local spam
global spam
global spam
