Академический Документы
Профессиональный Документы
Культура Документы
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
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.
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
a)Single Inheritance in Python
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
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 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
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
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
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.
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.
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
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")
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: