9 4 1 Single Inheritance Explained
Key Concepts
Single inheritance in Python involves several key concepts:
- Superclass and Subclass
- Inheriting Attributes and Methods
- Overriding Methods
- Accessing Superclass Methods
1. Superclass and Subclass
In single inheritance, a subclass inherits from a single superclass. The superclass is the class being inherited from, and the subclass is the class that inherits.
Example:
class Animal: def __init__(self, name): self.name = name def speak(self): return "Animal sound" class Dog(Animal): pass my_dog = Dog("Buddy") print(my_dog.name) # Output: Buddy print(my_dog.speak()) # Output: Animal sound
Analogy: Think of the superclass as a parent and the subclass as a child who inherits traits from the parent.
2. Inheriting Attributes and Methods
The subclass inherits all attributes and methods from the superclass. This allows the subclass to reuse and extend the functionality of the superclass.
Example:
class Vehicle: def __init__(self, make, model): self.make = make self.model = model def start(self): return "Engine started!" class Car(Vehicle): pass my_car = Car("Toyota", "Camry") print(my_car.make) # Output: Toyota print(my_car.start()) # Output: Engine started!
Analogy: Think of the subclass as a tool that comes with a set of pre-built features from the superclass.
3. Overriding Methods
The subclass can override methods inherited from the superclass. This allows the subclass to provide its own implementation of the method.
Example:
class Animal: def __init__(self, name): self.name = name def speak(self): return "Animal sound" class Dog(Animal): def speak(self): return "Woof!" my_dog = Dog("Buddy") print(my_dog.name) # Output: Buddy print(my_dog.speak()) # Output: Woof!
Analogy: Think of overriding as customizing a recipe while keeping the basic ingredients the same.
4. Accessing Superclass Methods
The subclass can access methods from the superclass using the super()
function. This is useful when you want to extend the functionality of the superclass method.
Example:
class Animal: def __init__(self, name): self.name = name def speak(self): return "Animal sound" class Dog(Animal): def speak(self): return super().speak() + " Woof!" my_dog = Dog("Buddy") print(my_dog.name) # Output: Buddy print(my_dog.speak()) # Output: Animal sound Woof!
Analogy: Think of super()
as a way to call the parent's version of a method before adding your own twist.
Putting It All Together
By understanding and using these concepts effectively, you can create more organized and reusable code using single inheritance in Python.
Example:
class Vehicle: def __init__(self, make, model): self.make = make self.model = model def start(self): return "Engine started!" class Car(Vehicle): def start(self): return super().start() + " Car engine started!" my_car = Car("Toyota", "Camry") print(my_car.make) # Output: Toyota print(my_car.start()) # Output: Engine started! Car engine started!