DEV Community

Aruna Arun
Aruna Arun

Posted on

Day 17: Python programming

1. What is Inheritance?
Inheritance allows one class (child / subclass) to acquire properties and methods of another class (parent / superclass).
*Code reuse
*Less duplication
*Easy maintenance

2. Basic Inheritance Example
class Parent:
def show(self):
print("This is parent class")
class Child(Parent):
pass
c = Child()
c.show()

3. Types of Inheritance
1. Single Inheritance
One parent → one child
class A:
def display(self):
print("Class A")
class B(A):
pass
obj = B()
obj.display()
2. Multilevel Inheritance
Grandparent → Parent → Child
class GrandParent:
def g(self):
print("Grand Parent")
class Parent(GrandParent):
def p(self):
print("Parent")
class Child(Parent):
def c(self):
print("Child")
obj = Child()
obj.g()
obj.p()
obj.c()
3. Hierarchical Inheritance
One parent → multiple children
class Parent:
def show(self):
print("Parent")
class Child1(Parent):
pass
class Child2(Parent):
pass
4. Multiple Inheritance
Multiple parents → one child
class A:
def showA(self):
print("Class A")
class B:
def showB(self):
print("Class B")
class C(A, B):
pass
obj = C()
obj.showA()
obj.showB()

4. super() Keyword
Used to call parent class methods and constructor.

Without super()
class A:
def init(self):
print("A constructor")
class B(A):
def init(self):
A.init(self)
print("B constructor")
B()

With super()
class A:
def init(self):
print("A constructor")
class B(A):
def init(self):
super().init()
print("B constructor")
B()

5. Method Overriding
Child class redefines parent method.
class Parent:
def show(self):
print("Parent method")
class Child(Parent):
def show(self):
print("Child method")

obj = Child()
obj.show()

6. Polymorphism
Same function name → different behavior.
1. Function Polymorphism
print(len("Python"))
print(len([1, 2, 3]))
2. Method Overriding (Polymorphism)
class Animal:
def sound(self):
print("Animal sound")
class Dog(Animal):
def sound(self):
print("Bark")
d = Dog()
d.sound()
3. Operator Overloading
Using magic methods.
class A:
def add(self, other):
return self.value + other.value

7. Method Resolution Order (MRO)
Order in which Python searches methods in multiple inheritance.
class A: pass
class B(A): pass
class C(B): pass
print(C.mro())

8. Abstract Base Class (Introduction)

Used to force child classes to implement methods.
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass

9. Real-Time Example
Vehicle Example
class Vehicle:
def start(self):
print("Vehicle started")
class Bike(Vehicle):
def start(self):
print("Bike started")
class Car(Vehicle):
def start(self):
print("Car started")
v = Vehicle()
b = Bike()
c = Car()
v.start()
b.start()
c.start()

Top comments (0)