【问题标题】:Refer a global variable that has same name as the local variable in Python引用一个与 Python 中的局部变量同名的全局变量
【发布时间】:2016-10-01 11:13:02
【问题描述】:

我是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()

【问题讨论】:

  • 你不能,也没有意义。您应该避免全局状态和名称阴影。
  • 你可以print(globals()["spam"]) 但不要。
  • 或者import sys; print(sys.modules[__name__].spam),但这仍然不是一个好主意
  • 你不能定义def scope_test(spam): ... return spam并运行spam = scope_test(spam)
  • @furas:OP 不希望函数修改全局 spam

标签: python


【解决方案1】:

这是不推荐的东西,如果您有兴趣问/做,我会回答它:

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

【讨论】:

    猜你喜欢
    • 2016-04-06
    • 2014-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多