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

Python Create a Subclass Using Inheritance

Python Create a Subclass Using Inheritance

Document Object Reference Manual Python3 Examples

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"

)

print

(

animal.

speak

(

)

)

Create an instance of the subclass

dog

=

Dog

(

"Buddy"

)

print

(

dog.

speak

(

)

)

Code analysis:

  1. Animal is a parent class with a constructor __init__used to initialize name attribute.speak The method returns a string representing the sound an animal makes.
  2. Dog is a subclass that inherits from Animal. It overrides the speak method and returns a string representing a dog barking.
  3. Created a Animal class animaland call the speak method, printing "Generic Animal makes a sound.".
  4. Created a Dog class dogand call the speak method, printing "Buddy barks.".

Output result:

Generic Animal makes a sound.
Buddy barks.

Document Object Reference Manual Python3 Examples