Python Define a Subclass That Inherits from a Parent Class and Override a Method in the Subclass
In Python, we can inherit from a parent class by defining a subclass, and override the parent class's methods in the subclass. A subclass can inherit all attributes and methods of the parent class, and can also override the parent class's methods as needed to implement different functionality.
Example
Define a parent class
class
Animal:
def
speak
(
self
)
:
(
"Animal speaks"
)
Define a subclass that inherits from the parent class
class
Dog
(
Animal
)
:
Override the parent class's speak method
def
speak
(
self
)
:
(
"Dog barks"
)
Create a parent class object
animal
=
Animal
(
)
animal.
speak
(
)
Create a subclass object
dog
=
Dog
(
)
dog.
speak
(
)
Code analysis:
Animalis a parent class in which aspeakmethod is defined, outputting "Animal speaks".DogIsAnimal's subclass, which inheritsAnimalall attributes and methods.- in
DogIn the class, we override thespeakmethod so that it outputs "Dog barks". - creation
Animalobject of the classanimaland call thespeakmethod is defined, outputting "Animal speaks". - creation
Dogobject of the classdogand call thespeakmethod, outputting "Dog barks".
Output result:
Animal speaks
Dog barks
Python3 Examples