Click here to Skip to main content
15,887,683 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I was trying one code of Python Inheritance but the code doesn't work, not sure why

What I have tried:

Here is what my code looks like -

class Animal(object):
    def __init__(self, nlegs=4):
        print '__init__ Animal'
        self.nlegs = nlegs

class Dog(Animal):
    def __init__(self, talk='Bahu Bhau'):
        print '__init__ Dog'
        self.talk = talk

class Goat(Animal):
    def __init__(self, talk='Bha Bha'):
        print '__init__ Goat'
        self.talk = talk


1. Why does my Dog not have n legs attribute.
2. Should I call Animal.__init__() from within Dog.__init__
3. What if I want to create a Dog with 6 Legs, is it needed to add additional arguments to the Dog.__init__ interface?

Any idea what is wrong with this code. This is actually a practice question that I was trying to solve, tried to search/dig multiple places and read this article on Python Inheritance to understand the issue behind this code but no luck.
Posted
Updated 26-Apr-22 4:01am
v6
Comments
Richard Deeming 26-Apr-22 8:37am    
If you want someone to help you solve a problem with your code, you need to describe what the problem is. Simply saying it "doesn't work" tells us nothing.

Click the green "Improve question" link and update your question to include a clear description of the problem, including the full details of any errors. Remember to indicate which line of your code the errors relate to.
Shruti Bongale 26-Apr-22 9:04am    
have improved the question.

1 solution

Inheritance at work (see Python Inheritance[^]):
Python
class Animal(object):
    def __init__(self, nlegs=4):
        self.nlegs = nlegs

class Dog(Animal):
    def __init__(self, talk='Bahu Bhau'):
        Animal.__init__(self)
        self.talk = talk

class Crow(Animal):
    def __init__(self, talk='Ka Ka'):
        Animal.__init__(self,2)
        self.talk = talk


c = Crow()
print(c.talk)
print(c.nlegs)
 
Share this answer
 
v2
Comments
Richard MacCutchan 26-Apr-22 8:50am    
I didn't realise Italian crows had four legs. :)
CPallini 26-Apr-22 9:04am    
Neither did I. :-D

BTW thank you.
Shruti Bongale 26-Apr-22 9:06am    
Now with some special power, the Crow has transformed into Goat #LoL ;)
CPallini 26-Apr-22 14:24pm    
The power of the OOP!
:-D

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900