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__(开发者_StackOverflow中文版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 {}
精彩评论