Skip to main content

Python Inheritance and polymorphism

Inheritance and polymorphism are key concepts in object-oriented programming (OOP) that enable code reusability and flexibility. They allow you to create complex systems by defining hierarchical relationships between classes and enabling objects to take on multiple forms.

Inheritance

Inheritance allows a new class (child or subclass) to inherit attributes and methods from an existing class (parent or superclass). This promotes code reuse and establishes a natural hierarchy between classes.

Example:

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

    def speak(self):
        raise NotImplementedError("Subclass must implement this 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!"

# Creating instances of subclasses
dog = Dog("Buddy")
cat = Cat("Whiskers")

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

In this example:

  • Animal is the parent class with a constructor and a method speak.
  • Dog and Cat are subclasses that inherit from Animal and implement the speak method.

Polymorphism

Polymorphism allows objects of different classes to be treated as objects of a common super class. It provides a way to use a single interface to represent different data types or classes.

Example:

class Bird:
    def fly(self):
        raise NotImplementedError("Subclass must implement this method")

class Sparrow(Bird):
    def fly(self):
        return "Sparrow flies high!"

class Penguin(Bird):
    def fly(self):
        return "Penguin can't fly!"

# Function that demonstrates polymorphism
def bird_flight(bird):
    print(bird.fly())

# Using polymorphism
sparrow = Sparrow()
penguin = Penguin()

bird_flight(sparrow)  # Output: Sparrow flies high!
bird_flight(penguin)  # Output: Penguin can't fly!

In this example:

  • Bird is a parent class with an abstract method fly.
  • Sparrow and Penguin are subclasses that implement the fly method.
  • The bird_flight function demonstrates polymorphism by accepting any object that is an instance of Bird and calling the fly method.

Method Overriding

Method overriding allows a subclass to provide a specific implementation of a method that is already defined in its superclass. This is a form of polymorphism.

Example:

class Vehicle:
    def move(self):
        return "Vehicle is moving"

class Car(Vehicle):
    def move(self):
        return "Car is driving"

class Boat(Vehicle):
    def move(self):
        return "Boat is sailing"

# Instances of subclasses
car = Car()
boat = Boat()

# Calling overridden methods
print(car.move())  # Output: Car is driving
print(boat.move())  # Output: Boat is sailing


The super() Function

The super() function allows you to call methods from the parent class in a subclass. This is useful for extending or modifying the behavior of inherited methods.

Example:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def display(self):
        return f"Name: {self.name}, Age: {self.age}"

class Student(Person):
    def __init__(self, name, age, student_id):
        super().__init__(name, age)
        self.student_id = student_id

    def display(self):
        parent_display = super().display()
        return f"{parent_display}, Student ID: {self.student_id}"

# Creating an instance of Student
student = Student("Alice", 20, "S12345")

# Calling the overridden method
print(student.display())  # Output: Name: Alice, Age: 20, Student ID: S12345

In this example:

  • Person is the parent class with an __init__ method and a display method.
  • Student is a subclass that extends Person by adding a student_id attribute.
  • The super().__init__(name, age) call ensures the name and age attributes are initialized in the Person class.
  • The display method in Student calls the display method in Person using super() and extends its functionality.

Summary

  • Inheritance: Allows a class to inherit attributes and methods from another class, promoting code reuse and establishing hierarchical relationships.
  • Polymorphism: Allows objects of different classes to be treated as objects of a common super class, enabling a single interface to represent different underlying forms.
  • Method Overriding: Provides a specific implementation of a method in a subclass that is already defined in its superclass.
  • super() Function: Used to call methods from the parent class in a subclass, useful for extending or modifying inherited behavior.

These concepts are fundamental to building modular, reusable, and maintainable code in Python.

Comments

Popular posts from this blog

TechUplift: Elevating Your Expertise in Every Click

  Unlock the potential of data with SQL Fundamental: Master querying, managing, and manipulating databases effortlessly. Empower your database mastery with PL/SQL: Unleash the full potential of Oracle databases through advanced programming and optimization. Unlock the Potential of Programming for Innovation and Efficiency.  Transform raw data into actionable insights effortlessly. Empower Your Data Strategy with Power Dataware: Unleash the Potential of Data for Strategic Insights and Decision Making.

Relationships between tables

In Power BI, relationships between tables are essential for creating accurate and insightful reports. These relationships define how data from different tables interact with each other when performing analyses or creating visualizations. Here's a detailed overview of how relationships between tables work in Power BI: Types of Relationships: One-to-one (1:1):   This is the most common type of relationship in Power BI. It signifies that one record in a table can have multiple related records in another table. For example, each customer can have multiple orders. Many-to-One (N:1):   This relationship type is essentially the reverse of a one-to-many relationship. Many records in one table can correspond to one record in another table. For instance, multiple orders belong to one customer. One-to-Many (1:N):   Power BI doesn't support direct one-to-many relationships.  One record in table can correspond to many records in another table.  Many-to-Many (N:N):  ...

SQL Fundamentals

SQL, or Structured Query Language, is the go-to language for managing relational databases. It allows users to interact with databases to retrieve, manipulate, and control data efficiently. SQL provides a standardized way to define database structures, perform data operations, and ensure data integrity. From querying data to managing access and transactions, SQL is a fundamental tool for anyone working with databases. 1. Basics of SQL Introduction : SQL (Structured Query Language) is used for managing and manipulating relational databases. SQL Syntax : Basic structure of SQL statements (e.g., SELECT, INSERT, UPDATE, DELETE). Data Types : Different types of data that can be stored (e.g., INTEGER, VARCHAR, DATE). 2. SQL Commands DDL (Data Definition Language) : CREATE TABLE : Define new tables. ALTER TABLE : Modify existing tables. DROP TABLE : Delete tables. DML (Data Manipulation Language) : INSERT : Add new records. UPDATE : Modify existing records. DELETE : Remove records. DQL (Da...