Class Variable Inheritance

Scott David Daniels Scott.Daniels at Acm.Org
Thu Dec 9 10:55:16 EST 2004


Brian Jones wrote:
> class a(object):
>     mastervar = []
>     def __init__(self):
>         print 'called a'
> 
> class b(a):
>     def __init__(self):
>         print 'called b'
>         self.mapvar()
>     def mapvar(self):
>         self.mastervar.append(['b'])
> 
> class c(b):
       mastervar = []   # Adding this should make things clearer
>     def __init__(self):
>         print 'called c'
>         self.mapvar()
>     def mapvar(self):
>         super(c, self).mapvar()
>         self.mastervar.append(['c'])
> 
> if __name__ == '__main__':
>     a1 = a()
>     b1 = b()
>     c1 = c()
>     d1 = c() # Call C again
       for object in a1, b1, c1, d1:
           print id(object.mastervar), object.mastervar

> What I don't understand is why mastervar gets modified by each _seperate 
> instance_ of classes that happen to extend the base class 'a'. Shouldn't 
> mastervar be contained within the scope of the inheriting classes?  Why 
> is it being treated like a global variable and being modified by the 
> other instances?
By over-riding mastervar in class c, I hope I've shown that a class 
variable is shared by all of its instances, but can be over-ridden by
a subclass's class variable.

--Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list