Python Single Inheritance
Single Inheritance in Python
Single inheritance is a fundamental concept in object-oriented programming (OOP) where a class (called the child class or subclass) inherits attributes and methods from only one parent class (called the base class or superclass). This model promotes code reuse and establishes a hierarchical relationship between classes.
Key Features of Single Inheritance
Single Parent Class: A child class can only inherit from one parent class, which helps avoid complexity and ambiguity that might arise from multiple inheritance.
Code Reusability: Child classes can reuse the methods and attributes defined in the parent class, reducing code duplication.
Method Overriding: Child classes can override methods from the parent class, providing specific implementations while still retaining access to the parent's functionality.
Extensibility: Single inheritance allows for the extension of the parent class's functionality by adding new methods or attributes in the child class.
Example of Single Inheritance
Here’s an example to illustrate single inheritance in Python:
Explanation of the Example
Parent Class (
Animal
):- The
Animal
class has an__init__
method that initializes thename
attribute and a methodspeak()
that returns a generic sound message.
- The
Child Class (
Dog
):- The
Dog
class inherits from theAnimal
class, meaning it has access to its attributes and methods. - The
speak()
method in theDog
class overrides the parent class'sspeak()
method to provide a specific implementation for dogs, returning a sound that a dog makes.
- The
Creating an Instance: An instance of the
Dog
class is created with the name "Buddy".Method Access: The
speak()
method of theDog
class is called, which returns "Buddy says Woof!", demonstrating how the child class can provide its own implementation while still being related to the parent class.
Summary
- Single inheritance involves a class inheriting from only one parent class, establishing a straightforward relationship.
- It promotes code reuse, allowing child classes to access and build upon the functionality provided by the parent class.
- Method overriding enables child classes to customize or extend the behavior of inherited methods.
If you have any further questions or need more examples, feel free to ask!