Python Inheritance: OOP for AI & Machine Learning
Master Python inheritance in OOP! Learn how child classes derive from parent classes, essential for building scalable AI and machine learning models. Boost code reuse.
6.4 Inheritance in Python
Inheritance is a fundamental concept in Object-Oriented Programming (OOP) that allows a class to inherit attributes and behaviors (methods) from another class. This promotes code reuse, simplifies software maintenance, and supports scalable program development.
What is Inheritance in Python?
Inheritance enables one class, known as the child class or subclass, to derive properties and methods from another class, the parent class or superclass. This mechanism facilitates code modularity and abstraction of common functionalities.
Real-Life Example of Inheritance
Consider a base class Animal
with methods like eat()
and sleep()
. Specific animal classes like Dog
and Cat
can inherit these behaviors and also define their own unique features, such as bark()
or meow()
.
Creating a Parent and Child Class in Python
Parent Class (Superclass):
class Animal:
def eat(self):
print("This animal eats food.")
Child Class (Subclass):
class Dog(Animal): # Dog inherits from Animal
def bark(self):
print("The dog barks.")
Example Usage:
d = Dog()
d.eat() # Inherited from Animal
d.bark() # Defined in Dog
Output:
This animal eats food.
The dog barks.
Types of Inheritance in Python
Python supports several types of inheritance, allowing for flexible class relationships.
1. Single Inheritance
A child class inherits from only one parent class.
class Writer:
def write(self):
print("Writing content...")
class Blogger(Writer): # Blogger inherits from Writer
def publish(self):
print("Publishing blog post.")
b = Blogger()
b.write()
b.publish()
2. Multiple Inheritance
A child class inherits from more than one parent class.
class Painter:
def paint(self):
print("Painting a picture.")
class Sculptor:
def sculpt(self):
print("Carving a statue.")
class Artist(Painter, Sculptor): # Artist inherits from Painter and Sculptor
def exhibit(self):
print("Displaying artworks.")
a = Artist()
a.paint()
a.sculpt()
a.exhibit()
3. Multilevel Inheritance
A class inherits from a child class, which in turn inherits from another class, creating a chain of inheritance.
class Organism:
def live(self):
print("Living...")
class Mammal(Organism): # Mammal inherits from Organism
def breathe(self):
print("Breathing air.")
class Human(Mammal): # Human inherits from Mammal
def think(self):
print("Thinking logically.")
h = Human()
h.live()
h.breathe()
h.think()
4. Hierarchical Inheritance
Multiple child classes inherit from a single parent class.
class Vehicle:
def start(self):
print("Starting vehicle...")
class Car(Vehicle): # Car inherits from Vehicle
def drive(self):
print("Driving a car.")
class Bike(Vehicle): # Bike inherits from Vehicle
def ride(self):
print("Riding a bike.")
c = Car()
b = Bike()
c.start()
c.drive()
b.start()
b.ride()
5. Hybrid Inheritance
A combination of two or more inheritance types.
class Machine:
def operate(self):
print("Operating machinery.")
class Computer(Machine): # Computer inherits from Machine
def compute(self):
print("Performing calculations.")
class Printer:
def print_doc(self):
print("Printing document.")
class OfficeDevice(Computer, Printer): # OfficeDevice inherits from Computer and Printer
def status(self):
print("Device ready.")
od = OfficeDevice()
od.operate()
od.compute()
od.print_doc()
od.status()
Method Resolution Order (MRO)
When multiple inheritance is involved, Python uses the Method Resolution Order (MRO) to determine the sequence in which classes are searched for a method. This ensures consistent behavior when a method is defined in multiple parent classes.
Checking MRO:
You can check the MRO of a class using the __mro__
attribute.
print(OfficeDevice.__mro__)
This will display the class resolution hierarchy, guiding how methods are found and executed.
Using super()
in Inheritance
The super()
function is used to call methods from the parent class, particularly useful within constructors (__init__
) to ensure that parent class initialization is performed.
Example:
class Vehicle:
def __init__(self, brand):
self.brand = brand
print("Vehicle initialized.")
class Truck(Vehicle):
def __init__(self, brand, capacity):
super().__init__(brand) # Call the parent class constructor
self.capacity = capacity
print("Truck initialized.")
def show_details(self):
print(f"Brand: {self.brand}, Capacity: {self.capacity} tons")
t = Truck("Volvo", 15)
t.show_details()
Output:
Vehicle initialized.
Truck initialized.
Brand: Volvo, Capacity: 15 tons
Summary
Feature | Description |
---|---|
Inheritance | Enables a class to acquire features (attributes and methods) from another class. |
Parent Class | The base class from which other classes inherit. |
Child Class | The class that inherits from the parent class. |
super() | Used to refer to and call methods of the parent class. |
MRO (__mro__ ) | Determines the order of method lookup in multiple inheritance scenarios. |
Reusability | Reduces code duplication by allowing reuse of parent class code. |
Related Concepts and Keywords
- Python inheritance tutorial
- Types of inheritance in Python
- Python single inheritance example
- Python multiple inheritance MRO
- Multilevel inheritance in Python
- Hierarchical inheritance Python
- Python hybrid inheritance
- Python
super()
function usage - Python class inheritance example
- Method resolution order in Python
Interview Questions
- What is inheritance in Python and why is it used?
- Explain the different types of inheritance supported in Python with examples.
- How does multiple inheritance work in Python and what is MRO?
- What is the difference between single and multilevel inheritance in Python?
- How does Python resolve method conflicts in multiple inheritance?
- What is the purpose of the
super()
function in Python inheritance? - Can a child class override methods from the parent class in Python? How?
- What is hybrid inheritance and how is it handled in Python?
- Explain the use of the
__mro__
attribute in Python classes. - How does inheritance promote code reusability and maintainability in Python?
Python Constructors & Instance Methods for AI Dev
Master Python constructors (__init__) and instance methods! Essential for object-oriented programming and building AI/ML applications efficiently. Learn best practices.
OOP Abstraction: Simplify Your Code with Key Concepts
Discover OOP Abstraction, a core principle for simplifying code. Learn how hiding implementation details enhances software development and maintainability for AI and ML.