Can I inherit member variables?

LorcanM lm401 at cam.ac.uk
Thu Sep 21 06:34:31 EDT 2006


Thanks for the reply.

I think there's a basic misunderstanding about the nature of
inheritance on my side.

What I want to do is instantiate the sub class (derived class) from
within the animal class. I then expect the sub class to have inherited
some basic properties that it knows it has (weight, colour). If I can
expand the example I gave previously to try to make this a little
clearer:

class animal:
  def __init__(self, weight, colour):
    self.weight = weight
    self.colour = colour

  def describeMyself(self, type, measurement):
    if type == 'bird':
      myanimal = bird(measurement)
    elif type == 'fish':
      myanimal = fish(measurement)

class bird(animal):
  def __init__(self, wingspan):
    self.wingspan = wingspan
    print "I'm a bird, weight %s, colour %s, wingspan %s" %
(self.weight, self.colour, self.wingspan)

class fish(animal):
  def __init__(self, length):
    self.length = length
    print "I'm a fish, weight %s, colour %s, length %s" % (self.weight,
self.colour, self.length)


It seems from what you say that the attributes (member variables) will
have to be passed forward explicitly like any other function call. This
of course is sensible, 'bird' or 'fish' are not tied to a specific
instance of 'animal' when they are instantiated.

Thanks for the help,


 Lorcan.


Benjamin Niemann wrote:


> You'll have to invoke the __init__ method of the superclass, this is not
> done implicitly. And you probably want to add the weight and colour
> attributes to your subclass in order to pass these to the animal
> constructor.
>
> class fish(animal):
>   def __init__(self, length, weight, colour):
>     animal.__init__(self, weight, colour)
>     self.length = length
>     print self.weight, self.colour, self.length
>




More information about the Python-list mailing list