At Thursday 21/9/2006 06:52, [EMAIL PROTECTED] wrote:

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 have to call the base __init__ too. If a bird is some kind of animal, it has a weight and a colour, and you have to provide them too:

class bird(animal):
  def __init__(self, weight, colour, wingspan):
    animal.__init__(self, weight, colour)
    self.wingspan = wingspan
    print self.weight, self.colour, self.wingspan

It seems from reading the newsgroups that a solution might be to
declare weight and colour as global variables in the class animal:

You can declare them as class attributes inside animal; this way they act like a default value for instance attributes.

class animal:
  weight = 0
  colour = ''
  ...

I'm not very experienced with OOP techniques, so perhaps what I'm
trying to do is not sensible. Does Python differ with regard to
inheritance of member variables from C++ and Java?

They are not called "member variables" but "instance attributes". They *are* inherited [1] but you have to set their value somewhere. Any object can hold virtually any attribute - this is *not* usually determined by the object's class. Base constructors ("initializer" actually) are *not* invoked automatically, so you must call them explicitely.

Read the Python Tutorial, it's easy and will teach you a lot of things about the language. You can read it online at <http://docs.python.org/tut/tut.html>

[1] kinda... remember that classes don't determine the available attributes; class attributes are inherited, and any attribute you set on an instance will be accessible by any method of the object, even above in the hierarchy.



Gabriel Genellina
Softlab SRL

        
        
                
__________________________________________________
Preguntá. Respondé. Descubrí.
Todo lo que querías saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
¡Probalo ya! http://www.yahoo.com.ar/respuestas

-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to