Please don't close this question if you don't really understand what's happening in this code. This is different than "Least Astonishment" and the Mutable Default Argument
In the following code, I defined a clone
method where it calls the "constructor" without parameters. But within the __init__
method, the value of the parameter keeps changing (see the WARNING
lines of the output). Why is that?
Code:
#!/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()
Output:
__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}