-2

I am currently learning how to program in Python I am stuck calling an attribute from a Parent class. In the example below, how can I call the attribute "name" on "daisy" to print the name. I always get an error "'Mammal' object has no attribute 'name'.

class Vertebrate:
    spinal_cord = True
    def __init__(self, name):
        self.name = name

class Mammal(Vertebrate):
    def __init__(self, name, animal_type):
        self.animal_type = animal_type
        self.temperature_regulation = True

daisy = Mammal('Daisy', 'dog')

print(daisy.name) 

here I want to print the name which has been defined in the Vertebrate class, but I always get an error "'Mammal' object has no attribute 'name'"

Peter P
  • 43
  • 5
  • I welcome you to SO. I wish you have great journey ahead with us. What you have tried and what error did you faced? Please mention that in the question. – Amazing Things Around You Jun 06 '19 at 08:12
  • 3
    Possible duplicate of [How to invoke the super constructor?](https://stackoverflow.com/questions/2399307/how-to-invoke-the-super-constructor) – kabanus Jun 06 '19 at 08:15

2 Answers2

0

You need to call super in the __init__ of Mammal, like this:

class Mammal(Vertebrate):
    def __init__(self, name, animal_type):
        super().__init__(name)
        self.animal_type = animal_type
        self.temperature_regulation = True

When __init__ of Mammal is called, it doesn't automatically call the __init__ of it's parent class, that's what super does here.

Eran
  • 2,324
  • 3
  • 22
  • 27
  • You will have to also notice that the parent class has not been derived from object. It will not let you work with the super constructor. That's something I notice on python2.7 – Kenstars Jun 06 '19 at 08:30
  • @Kenstars, That's true for python2, classes need to inherit from object there in order to be "new style classes". In python3 you don't need to inherit from object, nor do you need to call super with arguments (when the arguments are the default ones). I can only hope that a person learning python these days will do so with python3. :) – Eran Jun 06 '19 at 08:56
  • Thanks for that Eran, I'm one of those knuckleheads still stuck in python2.7. – Kenstars Jun 06 '19 at 13:06
0

When you assign an init function to the child class, it overrides the default init function of parent class being called. In such a case you need to explicitly call the parent class using the super function. You also need to assign the class Vertebrate to be a child of the class Object to be able to access all of the object's modules within it.

class Vertebrate(object):
    def __init__(self, name):
        self.name = name
    spinal_cord = True

class Mammal(Vertebrate):
    def __init__(self, name, animal_type):
        super(Mammal, self).__init__(name)
        self.animal_type = animal_type
        self.temperature_regulation = True

animal = Mammal("Daisy", "dog")

print animal.name 
Kenstars
  • 662
  • 4
  • 11