Introduction to Inheritance
lass to inherit attributes and methods from another class. It provides code reusability and a logical s
Understanding OOP
ted Programming (OOP) is a programming paradigm based on the concept of 'objects', which are ins
What is Inheritance?
eritance is a mechanism where a new class inherits attributes and methods from an existing class. E
ython
ss Parent:
def func1(self):
print('This is a parent function')
ss Child(Parent):
pass
= Child()
.func1() # This is a parent function
Single Inheritance
In single inheritance, a child class inherits from a single parent class.
Example:
```python
class Animal:
def speak(self):
print('Animal speaks')
class Dog(Animal):
def bark(self):
print('Dog barks')
my_dog = Dog()
my_dog.speak() # Animal speaks
my_dog.bark() # Dog barks
```
Multiple Inheritance
In multiple inheritance, a child class can inherit from multiple parent classes.
Example:
```python
class A:
def method_A(self):
print('Method A')
class B:
def method_B(self):
print('Method B')
class C(A, B):
pass
obj = C()
obj.method_A() # Method A
obj.method_B() # Method B
```
Multi-Level Inheritance
In multi-level inheritance, a class is derived from another class which is also derived from another c
Example:
```python
class Grandparent:
def method_gp(self):
print('Grandparent method')
class Parent(Grandparent):
def method_p(self):
print('Parent method')
class Child(Parent):
def method_c(self):
print('Child method')
obj = Child()
obj.method_gp() # Grandparent method
obj.method_p() # Parent method
obj.method_c() # Child method
The `super()` Function
`super()` function allows us to call methods of the superclass in the derived class.
Example:
```python
class Parent:
def __init__(self, name):
self.name = name
class Child(Parent):
def __init__(self, name, age):
super().__init__(name)
self.age = age
obj = Child('John', 20)
print(obj.name) # John
print(obj.age) # 20
```
Method Overriding
rriding allows a child class to provide a specific implementation of a method that is already defined i
self):
arent class method')
arent):
self):
hild class method')
# Child class method
Inheritance and Encapsulation
ods within a single unit (class). Inheritance interacts with encapsulation by allowing derived classes t
Quiz Questions
1. What function is used to call methods from the parent class in Python?
A) `parent()`
B) `super()`
C) `base()`
D) `child()`
2. Which type of inheritance allows a class to be derived from more than one base class?
A) Single Inheritance
B) Multi-Level Inheritance
C) Multiple Inheritance
D) Hierarchical Inheritance