全球字典具有变化价值

时间:2016-03-30 02:35:08

标签: python python-3.x

我有以下示例代码:

A = None       
class App(object):
    def __init__(self, a):
        global A
        A = a   
a = {'x': 1}
print(A)  # None

App(a)
print(A)  # {'x': 1}

a['x'] = 2
print(A)  # {'x': 2} # value change if dictionary

a = 2
print(A)  # {'x': 2} # value not change

但我不知道为什么全球A 一直在改变价值?请帮我知道这个

1 个答案:

答案 0 :(得分:0)

您在类方法中使用了行global A。这可以确保在那里引用的变量A与您在第一行中定义的全局A相同。如果你遗漏了那个语句,那么函数中就会定义一个新的局部变量A

运行类方法后,A现在引用a。因此,a的所有更改也适用于A

在最后一行中,您可以更改变量a的类型及其值。 A现在将失去对a的约束力。请参阅此答案以获得解释:"if you rebind the reference in the method, the outer scope will know nothing about it, and after you're done, the outer reference will still point at the original object."

相关问题