Can I inherit member variables?

Benjamin Niemann pink at
Thu Sep 21 12:57:27 CEST 2006

LorcanM wrote:

> 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
> 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)

Do you really want one animal instance to act both as bird and fish?
Wouldn't it be more sensible to instanciate either bird or fish (animal
being what is called an abstract class in other OOP languages)? bird and
fish would then have their own implementation of describeMyself() with
the 'print "I'm a..."' statement.

I must admit that I don't really understand what you are trying to

Benjamin Niemann
Email: pink at odahoda dot de

More information about the Python-list mailing list