Can I inherit member variables?

MonkeeSage MonkeeSage at gmail.com
Thu Sep 21 06:11:18 EDT 2006


l... at cam.ac.uk wrote:
> 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).

Animal is never initialized and you're not passing weight and color
into it anyway. You need something like:

class animal: # (object): # <- new-style class
  def __init__(self, weight, colour):
    self.weight = weight
    self.colour = colour

class bird(animal):
  def __init__(self, weight, color, wingspan):
    #super(bird, self).__init__(weight, color) # <- new-style init
    animal.__init__(self, weight, color) # <- old-style init
    self.wingspan = wingspan
    print self.weight, self.colour, self.wingspan

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

HTH,
Jordan




More information about the Python-list mailing list