Learn Python this summer Day 12

Learn Python this summer Day 12: Inheritance and Polymorphism

Welcome back! Yesterday, we learned about classes and objects in Python. Today, we’ll dive deeper into object-oriented programming concepts with inheritance and polymorphism. These concepts will help you create more flexible and reusable code. Let’s get started!

What is Inheritance?

Inheritance allows you to create a new class based on an existing class. The new class (child class) inherits attributes and methods from the existing class (parent class), allowing you to reuse code and create a hierarchical relationship between classes.

Creating a Child Class

To create a child class, specify the parent class in parentheses after the child class name.

Example:

class Animal:
    def __init__(self, name):
        self.name = name

    def speak(self):
        raise NotImplementedError("Subclass must implement abstract method")

class Dog(Animal):
    def speak(self):
        return f"{self.name} says Woof!"

class Cat(Animal):
    def speak(self):
        return f"{self.name} says Meow!"

dog = Dog("Buddy")
cat = Cat("Whiskers")

print(dog.speak())  # Output: Buddy says Woof!
print(cat.speak())  # Output: Whiskers says Meow!

Method Overriding

Child classes can override methods from the parent class. This allows you to provide a specific implementation for the method in the child class.

Example:

class Bird(Animal):
    def speak(self):
        return f"{self.name} says Chirp!"

bird = Bird("Tweety")
print(bird.speak())  # Output: Tweety says Chirp!

Using super()

The super() function allows you to call methods from the parent class within the child class.

Example:

class Vehicle:
    def __init__(self, make, model):
        self.make = make
        self.model = model

    def description(self):
        return f"{self.make} {self.model}"

class Car(Vehicle):
    def __init__(self, make, model, year):
        super().__init__(make, model)
        self.year = year

    def description(self):
        return f"{self.year} {super().description()}"

car = Car("Toyota", "Camry", 2020)
print(car.description())  # Output: 2020 Toyota Camry

What is Polymorphism?

Polymorphism allows you to use a unified interface for different data types. In Python, it means that you can use the same method name in different classes.

Example:

class Fish(Animal):
    def speak(self):
        return f"{self.name} says Blub!"

animals = [Dog("Buddy"), Cat("Whiskers"), Bird("Tweety"), Fish("Nemo")]

for animal in animals:
    print(animal.speak())

Practice Time!

Let’s put what we’ve learned into practice. Write a Python program that demonstrates inheritance and polymorphism.

# Defining the base class
class Employee:
    def __init__(self, name, salary):
        self.name = name
        self.salary = salary

    def work(self):
        return f"{self.name} is working."

# Defining subclasses
class Manager(Employee):
    def work(self):
        return f"{self.name} is managing the team."

class Developer(Employee):
    def work(self):
        return f"{self.name} is writing code."

class Intern(Employee):
    def work(self):
        return f"{self.name} is learning and assisting."

# Creating instances of each class
employees = [
    Manager("Alice", 90000),
    Developer("Bob", 80000),
    Intern("Charlie", 30000)
]

# Using polymorphism to call the work method on each instance
for employee in employees:
    print(employee.work())

Conclusion

Great job today! You’ve learned how to use inheritance and polymorphism in Python, which are powerful concepts in object-oriented programming. Tomorrow, we’ll dive into graphical user interfaces (GUIs) and learn how to create simple GUIs using tkinter. Keep practicing and having fun coding!

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *