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

Performance Optimization

Performance optimization in SQL is crucial for ensuring that your database queries run efficiently, especially as the size and complexity of your data grow. Here are several strategies and techniques to optimize SQL performance: Indexing Create Indexes : Primary Key and Unique Indexes : These are automatically indexed. Ensure that your tables have primary keys and unique constraints where applicable. Foreign Keys : Index foreign key columns to speed up join operations. Composite Indexes : Use these when queries filter on multiple columns. The order of columns in the index should match the order in the query conditions. Avoid Over-Indexing:  Too many indexes can slow down write operations (INSERT, UPDATE, DELETE). Only index columns that are frequently used in WHERE clauses, JOIN conditions, and as sorting keys. Query Optimization Use SELECT Statements Efficiently : SELECT Only Necessary Columns : Avoid using SELECT * ; specify only ...

DAX UPPER Function

The DAX UPPER function in Power BI is used to convert all characters in a text string to uppercase. This function is useful for standardizing text data, ensuring consistency in text values, and performing case-insensitive comparisons. Syntax: UPPER(<text>) <text>: The text string that you want to convert to uppercase. Purpose: The UPPER function helps ensure that text data is consistently formatted in uppercase. This can be essential for tasks like data cleaning, preparing text for comparisons, and ensuring uniformity in text-based fields. E xample: Suppose you have a table named "Customers" with a column "Name" that contains names in mixed case. You want to create a new column that shows all names in uppercase. UppercaseName = UPPER(Customers[Name]) Example Scenario: Assume you have the following "Customers" table: You can use the UPPER function as follows: Using the UPPER function, you can convert all names to uppercase: UppercaseName = ...

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.