如果您不真正理解此代碼中發生的事情,請不要關閉此問題。這與“Least Astonishment”和可變默認參數不同
在下面的代碼中,我定義了一個clone
方法,它調用不帶參數的“構造函數”。但是在該__init__
方法中,參數的值不斷變化(請參閱WARNING
輸出行)。這是為什麼?
代碼:
#!/usr/bin/env python3
class Foo:
def __init__(self, aDic = {}):
self.aDic = aDic
print("__init__")
if aDic:
print("WARNING: aDic is not empty {}".format(aDic))
self.printme()
def printme(self):
print("aDic = {}".format(self.aDic))
def clone(self, props):
print("Before calling Foo() without parameters")
newValue = Foo()
print("after calling Foo() without parameters")
newValue.printme()
print("props = {}".format(props))
print("props.get = {}".format(props.get("aDic", self.aDic)))
for k, v in props.get("aDic", self.aDic).items():
newValue.aDic[k] = v
return newValue
a = Foo(aDic = {"b": 2})
a.printme()
print()
c = a.clone({"aDic": {"b": 222}})
c.printme()
print()
a.printme()
print()
d = a.clone({"aDic": {"b": 2222}})
d.printme()
print()
輸出:
__init__
WARNING: aDic is not empty {'b': 2}
aDic = {'b': 2}
aDic = {'b': 2}
Before calling Foo() without parameters
__init__
aDic = {}
after calling Foo() without parameters
aDic = {}
props = {'aDic': {'b': 222}}
props.get = {'b': 222}
aDic = {'b': 222}
aDic = {'b': 2}
Before calling Foo() without parameters
__init__
WARNING: aDic is not empty {'b': 222}
aDic = {'b': 222}
after calling Foo() without parameters
aDic = {'b': 222}
props = {'aDic': {'b': 2222}}
props.get = {'b': 2222}
aDic = {'b': 2222}
在 中clone()
,您Foo()
不帶參數調用,newValue.aDic
參數列表中的共享字典也是如此。
然後您在內部改變該共享副本 ( newValue.aDic[k] = v
),因此Foo()
您從該clone()
函數獲得的所有s 都將看到這些更改。
您示例的修改版本說明了這一點。看看id
s 是如何相同的?
class Foo:
def __init__(self, aDic = {}):
self.aDic = aDic
def printme(self):
print(f"aDic({id(self.aDic)}) = {self.aDic}")
def clone(self, props):
newValue = Foo()
newValue.printme()
for k, v in props.get("aDic", self.aDic).items():
newValue.aDic[k] = v
return newValue
print("a")
a = Foo(aDic = {"b": 2})
a.printme()
print("c")
c = a.clone({"aDic": {"b": 222}})
c.printme()
print("d")
d = a.clone({"aDic": {"b": 2222}})
d.printme()
打印出來(例如)
a
aDic(4494684352) = {'b': 2}
c
aDic(4494684544) = {}
aDic(4494684544) = {'b': 222}
d
aDic(4494684544) = {'b': 222}
aDic(4494684544) = {'b': 2222}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句