在字典中通过引用传递值
Pass value by reference in dictionary
我有字典:
foo = {"a": self.x}
我想更改对象的 self.x
值,而不仅仅是字典中保存的值。我该怎么做?
你不能那样做,self.x
的结果作为值存储在字典中,例如 10
。这里 10
与您的实例无关,字典 foo = {"a": 10}
与实际对象之间也没有任何关系。
为了更改您的实例变量,您必须能够访问“实例”本身。像 :
class C:
def __init__(self):
self.x = 10
instance = C()
print(instance.x)
foo = {"a": instance}
foo['a'].x = 20
print(instance.x)
输出:
10
20
我有字典:
foo = {"a": self.x}
我想更改对象的 self.x
值,而不仅仅是字典中保存的值。我该怎么做?
你不能那样做,self.x
的结果作为值存储在字典中,例如 10
。这里 10
与您的实例无关,字典 foo = {"a": 10}
与实际对象之间也没有任何关系。
为了更改您的实例变量,您必须能够访问“实例”本身。像 :
class C:
def __init__(self):
self.x = 10
instance = C()
print(instance.x)
foo = {"a": instance}
foo['a'].x = 20
print(instance.x)
输出:
10
20