-1

I've tried reading a few different tutorials, but I still can't figure it out. I have two simple classes. Animal and cat.

class Animal:
    def __init__(self, name):
        self.name = name

class Cat(Animal):
    def __init___(self, age):
        self.age = age
        print('age is: {0}'.format(self.age))

    def talk(self):
        print('Meowwww!')



c = Cat('Molly')
c.talk()

Output is:

Meowwww!

The code runs, but I'm a little confused. I created an instance of the cat class with c = Cat('Molly'). So somehow by using "Molly" as an argument for the Cat() class instance, it feeds "Molly" to the original base class (Animal) instead of the Cat class instance I created? Why? So how do I feed the Cat class instance the age variable it requires?

I tried doing:

c = Cat('Molly', 10)

But it complains about too many arguments. And secondly, why doesn't the __init__ function of the Cat class get called? It should print "age is...". It just never does.

EDIT: Got it to work, thanks to Martijn Pieters! Here is the updated code (works with python3):

class Animal():
    def __init__(self, name):
        self.name = name
        print('name is: {0}'.format(self.name))


class Cat(Animal):
    def __init__(self, name, age):
        super().__init__(name)
        self.age = age
        print('age is: {0}'.format(self.age))

    def talk(self):
        print('Meowwww!')


c = Cat('Molly', 5)
c.talk()
Shivang Saxena
  • 195
  • 1
  • 2
  • 13

1 Answers1

6

You misspelled __init__:

def __init___(self, age):
#   12    345

That's 3 double underscores at the end, not the required 2.

As such, Python won't call it as it is not the method it is looking for.

If you want to pass in both age and name, give the method another argument, then call the parent __init__ with just the name:

class Cat(Animal):
    def __init__(self, name, age):
        super().__init__(name)
        self.age = age
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Although I believe Animal would also need to inherit from "object" to use super() (see the [note on super](https://docs.python.org/2/library/functions.html#super). Also, super() can only be called without arguments in Python 3.0+. Otherwise, the child class and self must be passed as well. Check out [this question](http://stackoverflow.com/questions/576169/understanding-python-super-and-init-methods) for more info. – AMacK Jun 27 '14 at 15:14
  • @AMacK: Yes, but the OP is using Python 3 here (using `print()` as a function). `object` is *implicit* in Python 3 (all classes are new-style). – Martijn Pieters Jun 27 '14 at 15:15
  • True, but the print() function can also be optionally used in previous versions. I don't think the implicit object parent goes back, though. – AMacK Jun 27 '14 at 15:19
  • @AMacK: no, it doesn't indeed. In Python 2 you'd have to use the explicit form of `super()` and inherit from `object`. – Martijn Pieters Jun 27 '14 at 15:23