Can I inherit member variables?

Benjamin Niemann pink at
Thu Sep 21 12:01:44 CEST 2006


lm401 at wrote:

> I'm trying to work with the following idea:
> class animal:
>   def __init__(self, weight, colour):
>     self.weight = weight
>     self.colour = colour
> class bird(animal):
>   def __init__(self, wingspan):
>     self.wingspan = wingspan
>     print self.weight, self.colour, self.wingspan
> class fish(animal):
>   def __init__(self, length):
>     self.length = length
>     print self.weight, self.colour, self.length
> So basically I have a base class (animal) that has certain attributes.
> When animal is inherited by a specific instance, further attributes are
> added, but I need to have access to the original attributes (weight,
> colour). When I run my code from within the derived class, self.weight
> and self.colour are not  inherited (although methods are inherited as I
> would have expected).

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

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


Benjamin Niemann
Email: pink at odahoda dot de

More information about the Python-list mailing list