我有以下示例代码:
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 一直在改变价值?请帮我知道这个
答案 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."