Weird side effect of default parameter

Robert Latest boblatest at yahoo.com
Thu May 3 15:47:37 EDT 2018


Hello,

I don't understand the behavior of the code below. Why does the dict property
"a" of both objects contain the same keys? This is only if "a=dict" is in
the initializer. If I put self.a = dict() into the init function, I get two
separate dicts



class Foo(object):
    def __init__(self, x, a=dict()):
        self.x = x
        self.a = a
        self.a[x] = x


c = Foo(1)
d = Foo(2)

print(c.__dict__)
print(d.__dict__)


robert



More information about the Python-list mailing list