Inheritance example in Python Object Oriented Programming | applied electronics engineering

Latest

Inheritance example in Python Object Oriented Programming

By Applied Electronics - Monday, May 23, 2016 No Comments
Inheritance is basic principle of object oriented programming. Python object oriented programming also supports inheritance. Inheritance is the property that an object of one class can inherit attributes of another class. Here we show you example of inheritance in python object oriented programming. If you don't know how to create class and object then see a concise Python class & object creation tutorial.


For example, consider two classes A and B as follows:

Inheritance example in Python Object Oriented Programmingclass A:

    def force(self, m, a):
        f = m*a
        return f

    def printer(self, txt):
        print(txt)


class B(A):

    def energy(self, m):
        c = 3 * (10^8)
        e = m*(c**2)
        return e

Notice how B is declared as subclass of A. An instance or object of B can now access the attributes of class A. For example, an instance of class B called b can access the printer method of class A. This is called inheritance.

>>> from science import A, B
>>> b = B()
>>> b.printer('print this')
print this

 The converse cannot be performed. For example an instance/object of class A, let it be a, cannot inherit methods of class B.

print this
>>> a = A()
>>> a.energy(3)
Traceback (most recent call last):
 File "<input>", line 1, in <module>
AttributeError: 'A' object has no attribute 'energy'

The inheritance happens up the class tree. Suppose we have another class C which is subclass B which is in turn subclass of A. See the example code below.

class A:

    def force(self, m, a):
        f = m*a
        return f

    def printer(self):
        print('this is class A printer')


class B(A):

    def energy(self, m):
        c = 3 * (10^8)
        e = m*(c**2)
        return e

    def printer(self):
        print('this is class B printer')


class C(B):

    def add(self, a, b):
        return a + b


If we create an instance c of class C and invoke the method called printer then which class printer method will be invoked, class B or class A? notice that both class A and B have printer method. It turns out that since class C is the subclass of B, the printer method in class B will be executed.

This is illustrated below.

>>> from science import A, B, C
>>> x = C()
>>> x.printer()
this is class B printer


No Comment to " Inheritance example in Python Object Oriented Programming "