# Single Inheritance
class Parent:
pass
class Child(Parent):
pass
# Multiple Inheritance
class Parent1:
pass
class Parent2:
pass
class Child(Parent1, Parent2):
pass
Smartphone
class can inherit from Phone
, Camera
, and Computer
.print(Child.__mro__) # Output: Tuple showing the order
print(Child.mro()) # Output: List showing the order
class A:
def greet(self):
print("A")
class B(A):
def greet(self):
print("B")
class C(A):
def greet(self):
print("C")
class D(B, C):
pass
d = D()
d.greet() # Output: "B" (because B is first in MRO)
print(D.mro()) # Output: [D, B, C, A, object]
# Diamond Structure: D -> B -> A and D -> C -> A
class A:
def process(self):
print("A")
class B(A):
def process(self):
print("B")
super().process()
class C(A):
def process(self):
print("C")
super().process()
class D(B, C):
pass
d = D()
d.process()
Output:
B
C
A
Explanation:
D
: D -> B -> C -> A -> object
.super()
in B
calls C
, not A
, because of the MRO.super()
in Multiple Inheritance__init__
methods are called.super()
in Constructorsclass Parent1:
def __init__(self):
print("Parent1 initialized")
super().__init__() # Calls Parent2's __init__
class Parent2:
def __init__(self):
print("Parent2 initialized")
super().__init__() # Calls object's __init__
class Child(Parent1, Parent2):
def __init__(self):
print("Child initialized")
super().__init__()
c = Child()
Output:
Child initialized
Parent1 initialized
Parent2 initialized
MRO Flow: Child -> Parent1 -> Parent2 -> object
.
class JSONMixin:
def to_json(self):
import json
return json.dumps(self.__dict__)
class Person:
def __init__(self, name):
self.name = name
class Employee(JSONMixin, Person):
def __init__(self, name, salary):
super().__init__(name)
self.salary = salary
emp = Employee("Alice", 50000)
print(emp.to_json()) # Output: {"name": "Alice", "salary": 50000}
class Parent1:
def greet(self):
print("Parent1")
class Parent2:
def greet(self):
print("Parent2")
class Child(Parent1, Parent2):
def greet(self):
Parent2.greet(self) # Explicitly call Parent2's method
c = Child()
c.greet() # Output: "Parent2"
super()
in __init__
.super().__init__()
in parent classes.Child.mro()
to verify the order.class Walker:
def walk(self):
print("Walking")
class Swimmer:
def swim(self):
print("Swimming")
class Flying:
def fly(self):
print("Flying")
class SuperHero(Walker, Swimmer, Flying):
pass
hero = SuperHero()
hero.walk() # Output: Walking
hero.swim() # Output: Swimming
hero.fly() # Output: Flying
super()
ensures cooperative inheritance.By mastering these concepts, you’ll write flexible and powerful Python code! 🚀