Can I inherit member variables?

Benjamin Niemann pink at odahoda.de
Thu Sep 21 06:01:44 EDT 2006


Hello,

lm401 at cam.ac.uk 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
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


HTH

-- 
Benjamin Niemann
Email: pink at odahoda dot de
WWW: http://pink.odahoda.de/



More information about the Python-list mailing list