Python Create a Subclass Using Inheritance
In Python, inheritance is an important feature of object-oriented programming. With inheritance, a subclass inherits the attributes and methods of its parent class, and can add new attributes and methods or override the parent's methods. Here is a simple example showing how to create a subclass using inheritance.
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 that inherits from Animal
class
Dog
(
Animal
)
:
def
speak
(
self
)
:
return
f
"{self.name} barks."
Create an instance of the parent class
animal
=
Animal
(
"Generic Animal"
)
(
animal.
speak
(
)
)
Create an instance of the subclass
dog
=
Dog
(
"Buddy"
)
(
dog.
speak
(
)
)
Code analysis:
Animalis a parent class with a constructor__init__used to initializenameattribute.speakThe method returns a string representing the sound an animal makes.Dogis a subclass that inherits fromAnimal. It overrides thespeakmethod and returns a string representing a dog barking.- Created a
Animalclassanimaland call thespeakmethod, printing "Generic Animal makes a sound.". - Created a
Dogclassdogand call thespeakmethod, printing "Buddy barks.".
Output result:
Generic Animal makes a sound.
Buddy barks.
Python3 Examples