Python Create a Subclass Using Inheritance
In Python, inheritance is an important feature of object-oriented programming. Through inheritance, a subclass can inherit the attributes and methods of a parent class, and can add new attributes and methods in the subclass, or override the methods of the parent class. The following is a simple example showing how to use inheritance to create a subclass.
Example
# Define a parent class
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return f"{self.name} makes a sound."
# Define a subclass, inheriting from Animal
class Dog(Animal):
def speak(self):
return f"{self.name} barks."
# Create an instance of the parent class
animal = Animal("Generic Animal")
print(animal.speak())
# Create an instance of the subclass
dog = Dog("Buddy")
print(dog.speak())
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return f"{self.name} makes a sound."
# Define a subclass, inheriting from Animal
class Dog(Animal):
def speak(self):
return f"{self.name} barks."
# Create an instance of the parent class
animal = Animal("Generic Animal")
print(animal.speak())
# Create an instance of the subclass
dog = Dog("Buddy")
print(dog.speak())
Code explanation:
Animalis a parent class, it has a constructor__init__, used to initializenameattribute.speakmethod returns a string representing the sound made by the animal.Dogis a subclass, inheriting fromAnimal. It overrides thespeakmethod, returning a string representing a dog's bark.- Created an instance of the
Animalclassanimal, and called thespeakmethod, output "Generic Animal makes a sound.". - Created an instance of the
Dogclassdog, and called thespeakmethod, output "Buddy barks.".
Output result:
Generic Animal makes a sound. Buddy barks.Other Extensions
Python3 Examples