🔧 Advanced Inheritance
Last Updated: 06 Sept 2025
super() function.
The super() function is used to access the parent class of a child class.It call The parent class constructor.
class Animal:
def __init__(self, name):
self.name = name
class Dog(Animal):
def __init__(self, name, breed):
# Animal.__init__(self, name) # Call parent constructor same as below
super().__init__(name) # Call parent constructor
self.breed = breed
def details(self):
print(f"{self.name} is a {self.breed}")
d = Dog("Tommy", "Labrador")
d.details()
Public Members in Inheritance
class Parent:
def __init__(self, name):
self.name = name # public
def display(self):
print("Parent name:", self.name)
class Child(Parent):
def show(self):
print("Child accessing:", self.name) # ✅ allowed (public)
c = Child("Amit")
c.display() # Parent name: Amit
c.show() # Child accessing: Amit
print(c.name) # ✅ Directly accessible
👉 Public members are freely inherited & used anywhere.
Protected Members in Inheritance
class Parent:
def __init__(self, age):
self._age = age # protected
class Child(Parent):
def show(self):
print("Child accessing protected age:", self._age)
c = Child(22)
c.show() # ✅ allowed inside subclass
print(c._age) # ⚠️ Works, but convention says "internal use only"
👉 Protected members cannot be directly accessed outside the class.(But can still be accessed outside, not recommended).
Private Members in Inheritance
class Parent:
def __init__(self, roll):
self.__roll = roll # private
def show_roll(self):
print("Parent Roll:", self.__roll)
class Child(Parent):
def try_access(self):
# print(self.__roll) ❌ ERROR (not accessible)
print("Access via parent method:")
self.show_roll() # ✅ Allowed using parent's method
c = Child(101)
c.try_access()
# print(c.__roll) ❌ Error
print(c._Parent__roll) # ✅ Name mangling hack (not recommended)
👉Private members are not directly inherited.Child class cannot access them directly.