class - Trouble understanding python inheritance arguments -


i've tried reading few different tutorials, still can't figure out. have 2 simple classes. animal , 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, i'm little confused. created instance of cat class c = cat('molly'). somehow using "molly" argument cat() class instance, feeds "molly" original base class (animal) instead of cat class instance created? why? how feed cat class instance age variable requires?

i tried doing:

c = cat('molly', 10) 

but complains many arguments. , secondly, why doesn't __init__ function of cat class called? should print "age is...". never does.

edit: got work, martijn pieters! here updated code (works 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() 

you misspelled __init__:

def __init___(self, age): #   12    345 

that's 3 double underscores @ end, not required 2.

as such, python won't call not method looking for.

if want pass in both age , name, give method argument, call parent __init__ name:

class cat(animal):     def __init__(self, name, age):         super().__init__(name)         self.age = age 

Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -