Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Define a Subclass That Inherits from a Parent Class and Override a Method in the Subclass

Python Define a Subclass That Inherits from a Parent Class and Override a Method in the Subclass

Document Object Reference Manual Python3 Examples

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

)

:

       

print

(

"Animal speaks"

)

Define a subclass that inherits from the parent class

class

Dog

(

Animal

)

:

   

Override the parent class's speak method

   

def

speak

(

self

)

:

       

print

(

"Dog barks"

)

Create a parent class object

animal

=

Animal

(

)

animal.

speak

(

)

Create a subclass object

dog

=

Dog

(

)

dog.

speak

(

)

Code analysis:

  1. Animal is a parent class in which a speak method is defined, outputting "Animal speaks".
  2. Dog Is Animal 's subclass, which inherits Animal all attributes and methods.
  3. in Dog In the class, we override the speak method so that it outputs "Dog barks".
  4. creation Animal object of the class animaland call the speak method is defined, outputting "Animal speaks".
  5. creation Dog object of the class dogand call the speak method, outputting "Dog barks".

Output result:

Animal speaks
Dog barks

Document Object Reference Manual Python3 Examples