Inheritance
Inheritance
Inheritance is a feature in object-oriented programming (OOP) that allows one class (child or
derived class) to inherit properties and behaviors (methods) from another class (parent or base
class).
Code reusability – You don't have to write the same code again.
Organization – You can create a hierarchy of classes.
# Child class
class Dog(Animal):
def bark(self):
print("Dog barks")
# Accessing methods
d.speak() # Inherited from Animal
d.bark() # Defined in Dog
✅ Full Code:
python
CopyEdit
# Parent class
class Animal:
def speak(self):
print("Animal speaks")
# Child class
class Dog(Animal):
def bark(self):
print("Dog barks")
# Accessing methods
d.speak() # Inherited from Animal
d.bark() # Defined in Dog
🧠 Line-by-Line Explanation:
# Parent class
This is a comment to indicate that the next block of code defines the parent (or base)
class.
class Animal:
def speak(self):
print("Animal speaks")
When the speak() method is called, this line prints the message "Animal speaks".
# Child class
This defines a new class Dog that inherits from the Animal class.
The Dog class will have access to all methods and attributes of the Animal class.
def bark(self):
This defines a method named bark() specifically for the Dog class.
It’s not part of Animal, so only Dog (and classes that inherit from it) will have it.
print("Dog barks")
A comment stating that the next line creates an object of the Dog class.
d = Dog()
Give me codes for defining a contact base class with contacts as a list and its constructor to
initialize its name and email address. now create a class supplier derived from contact and its
own constructor calling the constructor of its base class .
A base class Contact with a class variable list of contacts and a constructor to initialize
name and email.
A derived class Supplier that inherits from Contact and calls the base class constructor
using super().
# Derived class
class Supplier(Contact):
def __init__(self, name, email):
super().__init__(name, email) # Call the constructor of the base
class
# You can add more Supplier-specific initialization here if needed
🧪 Example Usage
# Create contact and supplier objects
c1 = Contact("Alice", "[email protected]")
s1 = Supplier("Bob's Supplies", "[email protected]")
Contact class:
Supplier class:
Let’s walk through each line of the code step by step so you understand exactly what’s
happening.
✅ Full Code:
# Base class
class Contact:
all_contacts = [] # Class variable to store all contact instances
# Derived class
class Supplier(Contact):
def __init__(self, name, email):
super().__init__(name, email) # Call the constructor of the base
class
# You can add more Supplier-specific initialization here if needed
🔍 Line-by-Line Explanation:
# Base class
A comment indicating that the next class is the base (or parent) class.
class Contact:
all_contacts = []
This is the constructor method, called automatically when you create a new Contact
object.
self refers to the current object being created.
name and email are input parameters.
self.name = name
self.email = email
Contact.all_contacts.append(self)
Adds the current object (self) to the shared class list all_contacts.
This allows tracking of every contact created from the Contact class or any subclass
(like Supplier).
# Derived class
A comment indicating the next class is a derived (child) class that will inherit from
Contact.
class Supplier(Contact):
super().__init__(name, email)
A comment suggesting you can add more code here to initialize other attributes specific
to Supplier.
✅ 1. Single Inheritance
One child class inherits from one parent class.
Simplest form of inheritance.
📌 Example:
class Animal:
def speak(self):
print("Animal speaks")
✅ 2. Multilevel Inheritance
A class is derived from a class that is already derived from another class (like a chain).
📌 Example:
class Animal:
def speak(self):
print("Animal speaks")
class Puppy(Dog): # Puppy inherits from Dog (and indirectly from Animal)
def weep(self):
print("Puppy weeps")
✅ 3. Hierarchical Inheritance
Multiple child classes inherit from the same parent class.
📌 Example:
class Animal:
def speak(self):
print("Animal speaks")
✅ 4. Multiple Inheritance
A class inherits from more than one parent class.
Can be complex and lead to method resolution order (MRO) issues if not handled
carefully.
📌 Example:
class Father:
def skills(self):
print("Good at gardening")
class Mother:
def skills(self):
print("Good at cooking")
c = Child()
c.skills() # Output: "Good at gardening" (because Father comes first)
✅ 5. Hybrid Inheritance
A combination of two or more types of inheritance.
May involve multiple and multilevel patterns.
Can become complex and use Python's MRO to resolve conflicts.
📌 Example:
class A:
def method(self):
print("Method from A")
class B(A):
pass
class C(A):
pass
🔍 Summary Table:
Type Description Example Classes
Single One child from one parent Dog(Animal)
Multilevel Child from a child (chain) Puppy(Dog(Animal))
Hierarchical Multiple children from one parent Dog(Animal), Cat(Animal)
Multiple One child from multiple parents Child(Father, Mother)
Hybrid Combination of above types D(B, C)
What are the differences between public , private and protected attributes?
🔓 1. Public
Definition: Accessible from anywhere — inside or outside the class.
How to Declare: Use a normal name without underscores.
Example:
class User:
def __init__(self):
self.name = "John" # public
user = User()
print(user.name) # ✅ Works
🔐 2. Private
class User:
def __init__(self):
self.__password = "secret" # private
def get_password(self):
return self.__password
user = User()
# print(user.__password) ❌ Error (AttributeError)
print(user.get_password()) # ✅ Works
Definition: Should be accessed only within the class and its subclasses.
How to Declare: Prefix the name with a single underscore (_).
Note: It's still accessible from outside, but developers treat it as a "do not touch" sign.
Example:
class User:
def __init__(self):
self._email = "[email protected]" # protected
class Admin(User):
def show_email(self):
return self._email # ✅ Works in subclass
admin = Admin()
print(admin._email) # 😐 Works, but discouraged
🔁 Summary Table