Вы находитесь на странице: 1из 10

Neel Sanjay Bhatt

Roll No:-07
SE Computer A

Experiment No: 6B
AIM: A Python program to demonstrate multiple inheritance and display the
order of execution of methods in several base classes according to MRO.
TOOLS USED: Python 3.4.3, Terminal
THEORY:
1)Explain Inheritance in Python with syntax

Inheritance is an important aspect of the object-oriented paradigm. Inheritance


provides code reusability to the program because we can use an existing class to
create a new class instead of creating it from scratch.

In inheritance, the child class acquires the properties and can access all the data
members and functions defined in the parent class. A child class can also provide its
specific implementation to the functions of the parent class. 

In python, a derived class can inherit base class by just mentioning the base in the
bracket after the derived class name.

Syntax

1. class derived-class(base class):  
2.     <class-suite> 

A class can inherit multiple classes by mentioning all of them inside the bracket.
Consider the following syntax.

Syntax

1. class derive-class(<base class 1>, <base class 2>, ..... <base class n>):  
2.     <class - suite>  
2)Explain what is constructor overriding and method overriding and how to
overcome
Method overriding:
Method overriding in action In Python method overriding occurs simply defining
in the child class a method with the same name of a method in the parent class.
When you define a method in the object you make the latter able to satisfy
that method call, so the implementations of its ancestors do not come in play.
Override means having two methods with the same name but doing different tasks.
It means that one of the methods overrides the other.
If there is any method in the superclass and a method with the same name in a
subclass, then by executing the method, the method of the corresponding class will
be executed.

How to overcome Method overriding:


One can overcome method overriding but avoiding naming of functions both base
class and derived class with same name.
A namespace is a syntactic container which permits the same name to be used in
different modules or functions and in classes and methods

Constructor Overriding:
When an instance of a class is initialized, the super-class state should be fully
initialized before it becomes visible to the subclass. Calling methods of the subclass
in the superclass' __init__ method violates this important invariant.
How to overcome Constructor overriding

Do not use methods that are subclassed in the construction of an object. For simpler
cases move the initialization into the superclass' __init__ method, preventing it being
overridden. Additional initialization of subclass should be done in
the __init__ method of the subclass. For more complex cases, it is advisable to use
a static method or function to manage object creation.
Alternatively, avoid inheritance altogether using composition instead

3)Explain the types of inheritance with syntax


There are five types of inheritance in python, we observe.

a)Single Inheritance in Python

A single Python inheritance is when a single class inherits from a class.

Syntax

class derived-class(base class):  
    <class-suite> 

1. >>> x=0
2. >>> class fruit:
3. def __init__(self):
4. global x
5. x+=1
6. print("I'm a fruit")
7. >>> class citrus(fruit):
8. def __init__(self):
9. super().__init__()
10. global x
11. x+=2
12. print("I'm citrus")
13. >>> x
1. >>> lime=citrus()
Output:

I’m a fruit
I’m citrus

b. Python Multiple Inheritance

Multiple Python inheritance are when a class inherits from multiple base classes.

Syntax:

1. class Base1:  
2.     <class-suite>  
3.   
4. class Base2:  
5.     <class-suite>  
6. .  
7. .  
8. .  
9. class BaseN:  
10.     <class-suite>  
11.   
12. class Derived(Base1, Base2, ...... BaseN):  
13.     <class-suite>  

1. >>> class Color:


2. pass
3. >>> class Fruit:
4. pass
5. >>> class Orange(Color,Fruit):
6. pass
7. >>> issubclass(Orange,Color) and issubclass(Orange,Fruit)
Output: True

c. Multilevel Inheritance in Python

Multi-Level inheritance is possible in python like other object-oriented languages.


Multi-level inheritance is archived when a derived class inherits another derived
class. There is no limit on the number of levels up to which, the multi-level
inheritance is archived in python.When one class inherits from another, which in turn
inherits from another, it is multilevel python inheritance.
Syntax

1. class class1:  
2.     <class-suite>   
3. class class2(class1):  
4.     <class suite>  
5. class class3(class2):  
6.     <class suite>  
Eg:
1. >>> class A:
2. x=1
3. >>> class B(A):
4. pass
5. >>> class C(B):
6. pass
7. >>> cobj=C()
8. >>> cobj.x
Output: 1

d. Hierarchical Inheritance in Python

When more than one class inherits from a class, it is hierarchical Python inheritance.

1. >>> class A:
2. pass
3. >>> class B(A):
4. pass
5. >>> class C(A):
6. pass
7. >>> issubclass(B,A) and issubclass(C,A)
Output: True

e. Hybrid Inheritance in Python

Hybrid Python inheritance is a combination of any two kinds of inheritance.

1. >>> class A:
2. x=1
3. >>> class B(A):
4. pass
5. >>> class C(A):
6. pass
7. >>> class D(B,C):
8. pass
9. >>> dobj=D()
10. >>> dobj.x
Output: 1

4)What is Method Resolution Order (MRO)


Method Resolution Order (MRO) is the order in which Python looks for a method in a
hierarchy of classes. Especially it plays vital role in the context of multiple inheritance
as single method may be found in multiple super classes.
Syntax: class.mro() or class.__mro__

Case 1
This is a simple case where we have class C derived from both A and B. When
method process() is called with object of class C then process() method in class A is
called.
Python constructs the order in which it will look for a method in the hierarchy of
classes. It uses this order, known as MRO, to determine which method it actually
calls.
It is possible to see MRO of a class using mro() method of the class.

Case 2
In this case, we create D from C and B. Classes C and B have process() method and
as expected MRO chooses method from C. Remember it goes from left to right. So it
searches C first and all its super classes of C and then B and all its super classes.
We can observe that in MRO of the output given below.

Case 3
Now, lets change the hierarchy. We create B and C from A and then D from B and C.
Method process() is present in both A and C. 
5)Explain polymorphism with examples
The word polymorphism means having many forms. In programming, polymorphism
means same function name (but different signatures) being uses for different types.

Polymorphism in addition operator

We know that the + operator is used extensively in Python programs. But, it does not
have a single usage.
For integer data types, + operator is used to perform arithmetic addition operation.
num1 = 1
num2 = 2
print(num1+num2)
Here, we can see that a single operator + has been used to carry out different
operations for distinct data types. This is one of the most simple occurrences of
polymorphism in Python.

Function Polymorphism in Python

There are some functions in Python which are compatible to run with multiple data
types.

One such function is the len() function. It can run with many data types in Python.
Let's look at some example use cases of the function.
Example 2: Polymorphic len() function

print(len("Programiz"))
print(len(["Python", "Java", "C"]))
print(len({"Name": "John", "Address": "Nepal"}))
o/p:
9
3
2

Class Polymorphism in Python

Polymorphism is a very important concept in Object-Oriented Programming.We can


use the concept of polymorphism while creating class methods as Python allows
different classes to have methods with the same name.

We can then later generalize calling these methods by disregarding the object we
are working with. Let's look at an example:

class Cat:
def __init__(self, name, age):
self.name = name
self.age = age

def info(self):
print(f"I am a cat. My name is {self.name}. I am {self.age} years old.")

def make_sound(self):
print("Meow")

class Dog:
def __init__(self, name, age):
self.name = name
self.age = age

def info(self):
print(f"I am a dog. My name is {self.name}. I am {self.age} years old.")

def make_sound(self):
print("Bark")

cat1 = Cat("Kitty", 2.5)


dog1 = Dog("Fluffy", 4)

for animal in (cat1, dog1):


animal.make_sound()
animal.info()
animal.make_sound()
Run Code
Output

Meow
I am a cat. My name is Kitty. I am 2.5 years old.
Meow
Bark
I am a dog. My name is Fluffy. I am 4 years old.
Bark

Here, we have created two classes Cat and Dog. They share a similar structure and
have the same method names info() and make_sound().
However, notice that we have not created a common superclass or linked the
classes together in any way. Even then, we can pack these two different objects into
a tuple and iterate through it using a common animal variable. It is possible due to
polymorphism.
A Python program to demonstrate multiple inheritance and display the order of
execution of methods in several base classes according to MRO.
Code:
class A:
x=10
def value(self):
print(self.x)

class B:
y=20
def val(self):
print(self.y)

class C(A,B):
def sum(self):
z=self.x+self.y
print(z)

print(C.mro())

Output:
[<class '__main__.C'>, <class '__main__.A'>, <class '__main__.B'>, <class
'object'>]

Conclusion:

Thus we have studied and implemented interitance and its different


types,Constructor overridding and method overridding,Polymorphism and its type
and Method Resolution Order (MRO).

Вам также может понравиться