Python中有任何类型的范围解析运算符吗?

时间:2018-12-28 12:48:58

标签: 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

2 个答案:

答案 0 :(得分:3)

Python没有与::运算符直接等效的方法(通常这类事情由点.处理)。要从外部作用域访问变量,请将其分配给其他名称,以免对其产生阴影:

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

答案 1 :(得分:0)

我不知道执行此操作的任何方式(而且我不是专家)。我可以想到的两个解决方案是给您的local x命名(例如xLoc),或者将global x放在参数中,例如:

x=50

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

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

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

这是在回答您的问题吗?