The code that I'm acttualy having the problem with is very long, so I made an example that displays my problem.
I have two classes that inherit from a base-class (BaseClass). Both of these classes add some elements to self.Dict. However, they seem to cross contaminate elements. I was expecting c0.Dict to return {'class0': 0} and c1.Dict to return {'class1': 1}. However they both return {'class0': 0, 'class1': 1}. Why do they cross contaminate?
class BaseClass :
def __init__ (self, _dict={}) :
self.Dict = _dict
class Class0 (BaseClass) :
def __init__ (self) :
BaseClass.__init__(self)
self.Dict['class0'] = 0
class Class1 (BaseClass) :
def __init__ (self) :
BaseClass.__init__(self)
self.Dict['class1'] = 1
c0 = Class0()
c1 = Class1()
print c0.Dict
print c1.Dict
You hit a python gotcha : mutable default arguments.
http://blog.objectmentor.com/articles/2008/05/22/pythons-mutable-default-problem
class BaseClass :
def __init__ (self, _dict=None) :
self.Dict = _dict or {}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With