Inheritance:
A mechanism in object-oriented programming where one class inherits the attributes and methods of another class.
Types of inheritance:
- Single Inheritance
- Multiple Inheritance
- Multilevel Inheritance
- Hierarchical Inheritance
- Hybrid Inheritance
1. Single Inheritance:
When a class inherits from only one parent class.
Program:
class Parent():
def greet(self):
print("Hello from Parent!")
class Daughter(Parent):
def play(self):
print("Daughter is playing")
daughter = Daughter()
daughter.greet() # Inherited from Parent class
daughter.play() # Defined in Daughter class
Output:
Hello from Parent!
Daughter is playing
2. Multiple Inheritance:
When a class inherits from more than one parent class.
Program:
class Father:
def car(self):
print("Father's car")
class Mother:
def cooking(self):
print("Mother cooking")
class Daughter(Father, Mother):
def bike(self):
print("Daughter's bike")
Rathna = Daughter()
Rathna.car() # From Father class
Rathna.cooking() # From Mother class
Rathna.bike() # From Daughter class
Output:
Father's car
Mother cooking
Daughter's bike
3. Multilevel Inheritance:
When a class inherits from a parent class, and that parent class is also inherited by another class.
Program:
class Grandpa():
def House(self):
print("Grandpa's House")
class Father(Grandpa):
def bike(self):
print("Father's bike")
class Daughter(Father):
def scooty(self):
print("Daughter's scooty")
Rathna = Daughter()
Rathna.bike() # Calls Father class method
Rathna.House() # Calls Grandpa class method
Output:
Father's bike
Grandpa's House
4. Hierarchical Inheritance:
When multiple classes inherit from a single parent class.
Program:
class Father():
def Money(self):
print("Father's money")
class Son(Father):
def game(self):
print("Son playing game")
class Daughter(Father):
def bike(self):
print("Daughter's bike")
S = Son()
S.Money() # Inherited from Father
S.game() # Defined in Son
D = Daughter()
D.Money() # Inherited from Father
D.bike() # Defined in Daughter
Output:
Father's money
Son playing game
Father's money
Daughter's bike
0 Comments