Simple way to understand how Inheritance works in Python


Inheritance is a way to reuse code of existing object. Differ with Java, Python have more flexible inheritance. We can derived from base class and overide as many as we want to. So what most simple implementation of inheritance in Python?

Open your Python console interpreter and start typing:

1
2
3
4
5
6
7
8
9
10
11
12
13
class A(object):
    def __init__(self):
        self.name = "yodi"
 
class B(A):
    def __init__(self):
        A.__init__(self)
 
a = A()
a.name

b = B()
b.name

On your console, it should be print results like this :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
>>> class A(object):
…     def __init__(self):
…             self.name = "yodi"

>>> class B(A):
…     def __init__(self):
…             A.__init__(self)

>>> a = A()
>>> a.name
‘yodi’
>>> b = B()
>>> b.name
‘yodi’

See how inheritance works here ?
Code should explain this easily 🙂

No?
Okay, let see at class A(). We have define self.name = “yodi” there.
So, basically, if we create instance from class A(), we should have access to name.

But, how about class B()?
Yes, we re-use / clone __init__ from A. So, when we create instance from class B(),
actually it derived from class A().

Got it ? 🙂


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.