Can I inherit member variables?
MonkeeSage
MonkeeSage at gmail.com
Thu Sep 21 07:15:24 EDT 2006
Hi Lorcan,
Mabye thinking of it like this will help: birds and fishes (I love that
word, even if it is incorrect) can _do_ all the things that all animals
have in common: eat, drink, die, reproduce, &c; but that is generic.
class animal(object):
def eat(self, food): pass
...
class bird(animal): pass
class fish(animal): pass
If you want to talk about a specific bird or fish, then you have to say
more than just that it is an animal. Now, if all animals have a weight
and a color, but not all have the same weight or color, then you want
to say that this bird or fish is an animal which is colored X and
weighes Y.
class animal(object):
def __init__(self, weight, colour):
self.weight = weight
self.colour = colour
class bird(animal): pass # __init__ from animal is called implicitly
class fish(animal): pass
Now what if a bird and a fish have other attributes that not all
animals share (or at least specialized versions)? Well then you need to
say this bird is an animal which is colored X and weighs Y, but unlike
other animals, has a wingspan or length of Z.
class animal(object):
def __init__(self, weight, colour):
self.weight = weight
self.colour = colour
class bird(animal):
# override __init__ so we can say what _this_ animal is like
def __init__(self, weight, color, wingspan):
super(bird, self).__init__(weight, color)
self.wingspan = wingspan
class fish(animal):
def __init__(self, weight, color, length):
super(fish, self).__init__(weight, color)
self.length = length
Does this make more sense?
Regards,
Jordan
More information about the Python-list
mailing list