Thursday, November 15, 2018

Inheritance continued...


In Python there are two types of Inheritance:

1. Multiple Inheritance
2. Multilevel Inheritance

Let's see each type with an example.


Multiple inheritance

In multiple inheritance, a class inherits the attributes and methods from more than one parent class. In a scenario there are two classes Multiplication and Division which has methods for multiplication and division of two numbers.

 class Multiplication():
  
    def multiply(self,x,y):
      
        result = x*y
        return result


class Division():
   
    def division(self,a,b):
       
        result = a/b
       
        return result


For a multiple inheritance we'd require a third class which will inherit both Multiplication and Division classes. Let's have a third class Calculation which inherits from Multiplication and Division classes.

class Calculation(Multiplication,Division):
   
    pass


Since this class doesn't have any functionality of its own we have simply used pass. When we instantiate Calculation class, using it's instance we can perform multiplication and division of two numbers. See the code below -

obj1= Calculation()

mul = obj1.multiply(30,20)
print("\nThe multiplied value is: " + str(mul))

div = obj1.division(30,20)   

print("\nThe divided value is: " + str(div))


The output of this program is shown below -





Multilevel inheritance

In this type of inheritance, a class can inherit from a child class or derived class. The following program implements multilevel inheritance.

class Person():
   
               
    def display_name(self,fname,lname):
       
        cname = fname +' '+ lname
        return cname
       
class joined(Person):
   
    pass
   
   
class resigned(joined):
   
    pass
   
   
per = joined()

res = resigned()

oop = per.display_name('Veevaeck','Swami')
print(oop+ " just joined the company")

oop1 = res.display_name('Veevaeck','Swami')

print(oop1+ " just left the company")

   
In the preceding example, you can see that class joined inherited from class Person and class resigned
inherited from class joined . The instance of class joined and class resigned can call the method display_name of class Person. Let's see the output:




Operator overloading in Python

Python operators work for built-in classes. But same operator behaves differently with different types. For example, the + operator will, perform arithmetic addition on two numbers, merge two lists and concatenate two strings.

This feature in Python, that allows same operator to have different meaning according to the context is called operator overloading.

So what happens when we use them with objects of a user-defined class? We will see after understanding operator overloading with an example.

Using a special method, we'll able to change the built-in behavior of the operator. The special method is surrounded by double underscores (__). Some people called it the dunder method. Let's take an example of the + operator, as shown in the following example:

res = 'A' + 'B'

print(res)

fname = 'Vee' + 'vaeck'

print(fname)

num = 7 + 7

print(num)

We can see a different behavior of the + operator. The integer number is added and the strings are concatenated. Depending upon the object you are working with, the + operator has different behavior. However, the + calling is a special method that runs in the background. In order to do addition of two integers, the + operator calls int.__add__(7,7) and for string addition + calls str.__add__(“Vee”, vaeck”). See the following lines of code :

val = int.__add__(4,6)

print(val)

val = str.__add__("Vee","vaeck")

print(val)

The output of both the programs is shown below -




Thus we can customize the addition using the __add__() method. Now let's see if operator overloading can be used for objects of a class. Consider the following example we have used before:

class Employee():
   
    def __init__(self,position):
       
        self.position = position
   
    def setPosition(self):
        self.position= position


    def getPosition(self):
        return self.position.title()
       
emp1 = Employee('tester')
emp2 = Employee('developer')

print(emp1+emp2)

In the last line we are adding the two instances of the Employee class. Let's see the output of this program:



The preceding output shows an error in the code as the + operator cannot be used for objects. Let's overload + operator to support addition of objects. When I use emp1+emp2, the + operator should add the positions of the two employees. Here is the code:

def __add__(self,other):
        result = self.position+ other.position
        return result

The preceding program is the same as the previous one except for the magic __add__()method. When we use emp1+emp2, then the + operator calls the __add__() method. The __add__() method accepts two instances as arguments. The syntax result = self.position+ other.position signifies the addition of position of two instances, which are emp1and emp2, in our case. Let's see the output:




We have successfully added the two class objects using a + operator, which by default gives error. Here I'll end today's discussion. Next we'll cover Decorators, till then keep learning Python as Python is easy to learn!



   



Share:

0 comments:

Post a Comment