Reputation: 172
I'm struggling with how I should interpret class inheritance. What does it actually do? As far as I know, it allows your class to:
Does this go both ways? If something is inherited, will it be able to read his inheriter as well?
Please give your answer in as much layman's terms as possible. I'm not an native Englisch speaker and I've never had proper programming education. Give me an explenation, not a definiton :]
Upvotes: 2
Views: 113
Reputation: 2166
Let's say you have a class called Animal
. In this class you have a method called walk
, that prints "Animal is walking"
Now you have 2 other classes:
1. Class Bird
that is inherited from Animal
. You can now add an additional method to it: fly
. This will print that a bird can fly.
2. Class Monkey
that is inherited from Animal
as well. You can now add an additional method to it: climb
. This will print that a monkey can climb trees.
Both Monkey and Bird derive from Animal, so they can walk, they have a same functionality/feature. But both have a distinct feature as well: birds can fly and monkeys can climb trees. So it takes sense, right?
The reverse is false, because not every Animal can fly or can climb trees.
EDIT: I exaplined it to you in terms of methods. But this can apply to variables as well. The Animal
class can have a weight
field. Which is accessible from both inherited classes: Monkey
and Bird
.
But Monkey
can also have a field called max_power
and Bird
can have a class variable called max_fly_altitude
. This fields are unique for these certain types of animal and NOT for the generic Animal
. Which can also be a crocodile. And a crocodile can't fly to have a max_fly_altitude
attribute.
Upvotes: 2
Reputation: 32197
Inheritance does not work both ways. Here is what I mean:
If you have a class called Father
and another class called Son
which inherits from father as class Son(Father)
, then Son
can use all the methods from the Father
class but the Father
cannot use the methods from the Son
class.
class A:
def get_val(self):
return 5
class B(A):
def num(self):
return 3
>>> a = A()
>>> b = B()
>>> a.get_val()
5
>>> b.num()
3
>>> b.get_val()
5
>>> a.num()
Attribute Error: A instance has no attribute 'num'
class Musician:
def get_type(self):
return 'musician'
class Pianist(Musician):
def get_prof(self):
return 'pianist'
>>> m = Musician()
>>> p = Pianist()
>>> m.get_type()
'musician'
>>> p.get_type()
'musician'
>>> p.get_prof()
'pianist'
>>> m.get_prof()
Attribute Error: Musician instance has no attribute 'get_prof'
Upvotes: 1