Inheritance permits new classes to inherit features from existing classes, decreasing redundancy and reusing code. Polymorphism lets objects of diverse types share the same interface, empowering methods to be executed unexpectedly based on the object type. This decreases the code required and streamlines upkeep.
Inheritance could be a feature of object-oriented programming that permits one class to acquire characteristics from another class. In other words, inheritance permits a class to be characterized in terms of another class, which makes it simpler to make and keep up an application.
Polymorphism allows objects of different types to be treated similarly. In other words, polymorphism allows objects to be treated as a single type of object, even if they are of different types. This means that a single set of code can handle any object, even if the objects are of different types.
These are the inheritance types in python.
Inheritance in Python refers to the process by which one class can acquire the attributes and methods of another class. This is done by creating an inheritance relationship between the two classes. The class that is doing the inheriting is referred to as the child class, and the class that is being inherited from is referred to as the parent class. Polymorphism in Python is the ability of one object to take on multiple forms. This is done by creating multiple classes inherited from a single base class. Each class can then be used interchangeably, as they all share the same interface. This allows for a great degree of flexibility when it comes to programming. To demonstrate how to work with inheritance and polymorphism in Python, consider the following inheritance in python example of a class hierarchy for a game character.
class Character:
def **init**(self, health, attack):
self.health = health
self.attack = attack
class Wizard(Character):
def **init**(self, health, attack, magic):
super().**init**(health, attack)
self.magic = magic
class Warrior(Character):
def **init**(self, health, attack, magic):
super().**init**(health, attack,magic)
This code creates a class hierarchy for a game character. It starts with the base class Character, which has two attributes: health and attack. It then creates two child classes, Wizard and Warrior, which both inherit from the Character. The Wizard class adds a new attribute, magic, while the Warrior class does not add any additional attributes. This allows different types of characters to be created using the same interface.
class Animal:
"""A generic animal"""
def __init__(self, name):
self.name = name
class Dog(Animal):
"""A dog, a sub-class of Animal"""
def bark(self):
print("Woof!")
fido = Dog("Fido")
fido.bark() # prints "Woof!"
This code creates a class Animal and a class Dog, which is a sub-class of Animal. The Dog class inherits the init method from Animal and adds its bark() method. The code then creates an instance of Dog, named Fido, and calls the bark() method on it.
def print_name(obj):
print(obj.name)
fido = Dog("Fido")
bob = Cat("Bob")
print_name(fido) # prints "Fido
This code demonstrates polymorphism in Python. The function print_name() takes an object as a parameter and prints out the object's name. The print_name() function can be used with any object with the name attribute, regardless of its class. In this example, it is used with a Dog and a Cat object, both subclasses of Animals.
Compile-Time Polymorphism (Static Binding):
In Python, compile-time polymorphism is primarily achieved through function overloading, although Python does not support true function overloading. However, you can define functions with the same name in Python, but only the latest defined function will be considered.
def add(a, b):
return a + b
def add(a, b, c):
return a + b + c
result = add(2, 3) # Error: Only the latest defined function is available
Run-Time Polymorphism (Dynamic Binding):
Run-time polymorphism in Python is typically achieved through method overriding. You can override methods in a subclass to provide specific implementations. The method that gets called is determined at runtime based on the object's actual type.
class Animal:
def make_sound(self):
print("Animal makes a sound")
class Dog(Animal):
def make_sound(self):
print("Dog barks")
my_animal = Dog()
my_animal.make_sound() # Calls the overridden method in the Dog class
Interface Polymorphism (Polymorphism through Duck Typing):
Python follows a concept called "duck typing," which is a form of interface polymorphism. If an object behaves like a particular interface (has the required methods and attributes), it can be treated as an instance of that interface.
class Bird:
def fly(self):
pass
class Sparrow(Bird):
def fly(self):
print("Sparrow flies")
class Airplane:
def fly(self):
print("Airplane flies")
def perform_flight(flying_object):
flying_object.fly()
sparrow = Sparrow()
airplane = Airplane()
perform_flight(sparrow) # Output: Sparrow flies
perform_flight(airplane) # Output: Airplane flies
Operator Overloading:
Python supports operator overloading by defining special methods with double underscores (e.g., __add__, __sub__, __eq__, etc.). These methods allow you to define how operators should behave for objects of your class.
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
v1 = Vector(1, 2)
v2 = Vector(3, 4)
v3 = v1 + v2 # Calls the __add__ method, resulting in v3 = Vector(4, 6)
Parametric Polymorphism (Generics):
Python supports parametric polymorphism through the use of generics using type hints and annotations. You can use type variables to indicate that a function or class can work with various data types.
from typing import TypeVar
T = TypeVar('T')
def print_item(item: T):
print(item)
print_item(42) # Works with integers
print_item("Hello") # Works with strings
Python provides flexibility in achieving different types of polymorphism, making it a versatile language for object-oriented programming.
Inheritance and polymorphism are useful tools for software development and object-oriented programming. However, there are several limitations to be aware of when using inheritance and polymorphism.
Inheritance in object-oriented programming permits one class to inherit characteristics from another, resulting in less demanding code reuse, the creation of hierarchical classifications, and extensibility. Polymorphism empowers distinctive object types to share the same interface, driving the execution of more non-specific algorithms, more adaptable programs, and fewer lines of code. In any case, inheritance can increment program complexity and lead to tight coupling, whereas polymorphism can lead to investigating challenges and execution issues.
Answer:b. Inheritance
Answer:d. To allow a class to use the methods and properties of another class
Answer:d. Superclass
Answer:d. To replace the functionality of an existing method
Related Tutorials to watch
Top Articles toRead
Read