首页 > 解决方案 > Python中的任何类型的范围解析运算符?

问题描述

当还有一个同名的局部变量时,有什么办法可以让python解释器专门选择全局变量?(就像 C++ 有 :: 运算符)

x=50

def fun():
    x=20
    print("The value of local x is",x)

    global x
    #How can I display the value of global x here?
    print("The value of global x is",x)

print("The value of global x is",x)
fun()

功能块内的第二个打印语句应显示全局 x 的值。

File "/home/karthik/PycharmProjects/helloworld/scope.py", line 7

global x
^

SyntaxError: name 'x' is used prior to global declaration

Process finished with exit code 1

标签: python

解决方案


Python 没有直接等价于::运算符(通常这种事情由 dot 处理.)。要从外部范围访问变量,请将其分配给不同的名称以不隐藏它:

x = 50

def fun():
    x = 20
    print(x)  # 20

    print(x_)  # 50

print(x)  # 50
x_ = x
fun()

但是,如果没有对此进行破解,Python当然不会是Python......你所描述的实际上是可能的,但我不推荐它:

x = 50

def fun():
    x = 20
    print(x)  # 20

    print(globals()['x'])  # 50

print(x)  # 50
fun()

推荐阅读