What is Inheritance?
Inheritance is a way to create a new class that is a modified version of an existing class. The new class is called the subclass, and the existing class is the superclass.
The subclass inherits attributes and behavior methods from the superclass and can have additional attributes and behavior methods of its own. This allows you to reuse code and helps to keep your code organized and easy to maintain.
How to Use Inheritance in Python
To create a subclass in Python, you use the class
keyword followed by the name of the subclass, and then include the name of the superclass in parentheses. For example:
class Subclass(Superclass):
# code goes here
The subclass will inherit all of the attributes and behavior methods of the superclass. You can then add additional attributes and behavior methods to the subclass as needed.
Here is an example of a simple inheritance hierarchy in Python:
class Pet:
def __init__(self, name, species):
self.name = name
self.species = species
def make_sound(self):
print("Some generic sound")
class Dog(Pet):
def __init__(self, name, breed):
super().__init__(name, species="Dog")
self.breed = breed
def make_sound(self):
print("Bark")
In this example, the Pet
class is the superclass, and the Dog
class is the subclass. The Dog
class inherits the name
and species
attributes from the Pet
class, and has an additional attribute called breed
. The Dog
class also has its own version of the make_sound
method, which overrides the version inherited from the Pet
class.
Polymorphism
Polymorphism is the ability of a subclass to override or extend the behavior of a superclass. This is useful because it allows you to create subclasses that are specialized versions of the superclass, but that still retain the basic behavior of the superclass.
In the example above, the Dog
class overrides the make_sound
method of the Pet
class. This means that when you call the make_sound
method on a Dog
object, it will use the version of the method defined in the Dog
class, rather than the version inherited from the Pet
class.
Here is an example of using polymorphism in Python:
pets = [Pet("Fluffy", "Cat"), Dog("Buddy", "Labrador")]
for pet in pets:
pet.make_sound()
This code will output the following:
Some generic sound
Bark
The first Pet
object uses the version of the make_sound
method inherited from the Pet
class, while the second Dog
object uses the version of the make_sound
method defined in the Dog
class.
- Create a telegram bot step by step using python - June 2, 2023
- Easy way to create a database in MySQL - April 27, 2023
- 5 Unique Hackathon Project Ideas: Creative and Innovative - March 27, 2023