Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble with Python Inheritance

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 
like image 250
rectangletangle Avatar asked Jan 20 '23 18:01

rectangletangle


1 Answers

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 {}
like image 191
bobflux Avatar answered Jan 28 '23 14:01

bobflux