Class Variable Inheritance

Ken Rowlands kenrowlands at freeuk.com
Wed Dec 8 20:17:10 EST 2004


On Wed, 08 Dec 2004 15:55:09 -0900, Brian Jones wrote:

> I'm sure the solution may be obvious, but this problem is driving me 
> mad.  The following is my code:
> 
> 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):
> 
> 	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
> 
> 	print a1.mastervar
> 	print b1.mastervar
> 	print c1.mastervar
> 	print d1.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?
> 
> 
> Thanks,
> 
> Brian "bojo" Jones


Brian,

This is the first time I've responded to a post in this newsgroup so bear
with me.

First of all I believe that the place you declare mastervar is important.
As you have placed it above (or outside) any class methods/functions it
becomes a class variable. This gives it class scope and ALL instances of
that class (and sub-classes I think) will reference the SAME variable. If,
instead, you declare it inside the __init__ function of the class a object
it will be an instance variable and inheritable.

Secondly, in order to inherit methods and functions from base classes it
is important to remember to call the base class __init__ function in the
sub-class __init__ function.

If you do both these things, that is declare mastervar as 'self.mastervar
= []' inside class a.__init__ and call a.__init__ from b.__init__ (and
likewise for b in c) then you should get the expected result. I hope.

All I can say at this point is that I and not what you would call a
programmer, and I could be quite wrong in my explanation. However if this
doesn't help then there are many folk here who are better qualified to
give you the correct solution.


Regards



More information about the Python-list mailing list