What is inheritance and
its types with examples?
Ans:-Inheritance:-It 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 axquires the properties and can access
all the data members and functions defined in the parent class.
SYNTAX:-
Class derived-class(base class):
<class-suite>
EXAMPLE:-
class Animal:
def
speak(self):
print(“Animal
speaking”)
class Dog(Animal):
def
bark(self):
print(“dog
barking”)
d=Dog()
d.bark()
d.speak()
(i)MULTI-LEVEL INHERITANCE:-Multi-level inheritance is possible
in Python like other object-oriented languages.Multi-level inheritance is
achieved 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 achieved in
python.
SYNTAX:-
class class1:
<class-suite>
class class2(class1):
<class suite>
class class3(class2):
<class suite>
EXAMPLE:-
class Animal:
def
speak(self):
print(“Animal
speaking”)
class Dog(Animal):
def
bark(self):
print(“dog
barking”)
class DogChild(Dog):
def
eat(self):
print(“eating
bread…”)
d=DogChild()
d.bark()
d.speak()
d.eat()
(ii)MULTIPLE INHERITANCE:-Python provides us the flexibility
to inherit multiple base classes in the child class.
SYNTAX:-
class Base1:
<class-suite>
class Base2:
<class-suite>
class BaseN:
<class-suite>
Class
Derived(Base1,Base2,……..BaseN):
<class-suite>
EXAMPLE:-
class Calculation1:
def
Summation(self,a,b):
return
a+b;
class Calculation2:
def
Multiplication(self,a,b):
return
a*b;
class Derived(Calculation1,Calculation2):
def
Divide(self,a,b):
return
a/b;
d=Derived()
print(d.Summation(10,20))
print(d.Multiplication(10,20))
print(d.Divide(10,20))