Spex3
    

Inheritance in Python: Single Inheritance 🏛️


    

    

Inheritance is a key concept in Object-Oriented Programming (OOP) that allows a class to reuse properties and methods from another class.

✅ Single Inheritance means a child class inherits from a single parent class.

1️⃣ What is Single Inheritance?
📌 A child class (subclass) inherits attributes and methods from a parent class (superclass).
📌 The child class can add new features or override existing ones.

2️⃣ Defining a Parent and Child Class
# Parent class
class Animal:
def __init__(self, name):
self.name = name # Attribute

def speak(self):
return "Animal makes a sound"

# Child class (inherits from Animal)
class Dog(Animal):
def speak(self): # Method overriding
return "Woof! Woof!"

# Creating objects
dog = Dog("Buddy")
print(dog.name) # Output: Buddy (inherited from Animal)
print(dog.speak()) # Output: Woof! Woof! (overridden method)
🔹 Dog(Animal) → Dog inherits from Animal.
🔹 Dog inherits the name attribute from Animal.
🔹 The speak() method is overridden in Dog.

3️⃣ Adding New Methods in Child Class

class Cat(Animal):
def speak(self):
return "Meow!"

def jump(self): # New method in child class
return f"{self.name} is jumping!"

cat = Cat("Whiskers")
print(cat.speak()) # Output: Meow!
print(cat.jump()) # Output: Whiskers is jumping!
🔹 Cat class inherits from Animal.
🔹 Cat has a new method jump().

4️⃣ Using super() to Call Parent Methods
📌 super() is used to call the parent class’s methods inside the child class.


class Bird(Animal):
def __init__(self, name, color):
super().__init__(name) # Call parent constructor
self.color = color # New attribute

def speak(self):
return "Chirp! Chirp!"

def info(self):
return f"{self.name} is a {self.color} bird."

bird = Bird("Parrot", "green")
print(bird.info()) # Output: Parrot is a green bird.
print(bird.speak()) # Output: Chirp! Chirp!
🔹 super().__init__(name) calls Animal’s constructor.
🔹 Bird inherits name but adds a new attribute color.

5️⃣ Summary
Concept Description
Parent Class The base class from which another class inherits.
Child Class The derived class that inherits from the parent.
Method Overriding A child class redefines a method from the parent.
super() Calls the parent’s methods from the child class.


6️⃣ When to Use Single Inheritance?

✅ When a new class needs some features of an existing class but also requires its own features.

✅ When you want to reuse code and avoid redundancy.


    Date: 2025-03-24 00:00:00.000000