0% found this document useful (0 votes)
12 views

Python Inheritance (1)

Uploaded by

pugazhm125
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Python Inheritance (1)

Uploaded by

pugazhm125
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Inheritance in Python

Definition:
 It is a mechanism that allows you to create a hierarchy of classes that share a
set of properties and methods by deriving a class from another class.
 Inheritance is the capability of one class to derive or inherit the properties
from another class.
Syntax:
Class BaseClass:
{Body}
Class DerivedClass(BaseClass): # Inheritance
{Body}
1) Single Inheritance:
A child class inherits from a single parent class.

Example:
class Animal():
def speak(self):
print("Animal speaks")

class Dog(Animal): #Single Inheritance


def bark(self):
print("Dog barks")
2) Multiple Inheritance:
A child class inherits from more than one parent class.
Example:
class Animal:
def speak(self):
print("Animal speaks")

class Pet:
def show_affection(self):
print("Pet shows affection")

class Dog(Animal, Pet): # Multiple Inheritance


def bark(self):
print("Dog barks")
3) Multilevel Inheritance:
A child class inherits from a parent class, which in turn inherits from
another parent class.

Example:
class Animal:
def speak(self):
print("Animal speaks")
class Mammal(Animal): #Multilevel Inheritance
def walk(self):
print("Mammal walks")
class Dog(Mammal): #Multilevel Inheritance
def bark(self):
print("Dog barks")
4) Hierarchical Inheritance:
Multiple child classes inherit from a single parent class.
Example:
class Animal:
def speak(self):
print("Animal speaks")
class Dog(Animal): # Hierarchical Inheritance
def bark(self):
print("Dog barks")
class Cat(Animal): # Hierarchical Inheritance
def meow(self):
print("Cat meows")
5) Hybrid Inheritance:
A combination of two or more types of inheritance. It often involves
multiple inheritance to achieve complex inheritance structures.
Example:
class Animal:
def speak(self):
print("Animal speaks")
class Mammal(Animal): #Single Inheritance
def walk(self):
print("Mammal walks")
class Pet: # Multilevel Inheritance
def show_affection(self):
print("Pet shows affection")
class Dog(Mammal, Pet): #Multiple Inheritance
def bark(self):
print("Dog barks")

You might also like