我是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()
答案 0 :(得分:2)
这是不推荐的东西,如果你好奇地想要/做的话我会回答它:
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