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

Python Using Abstract Classes to Define Interfaces

Python Using Abstract Classes to Define Interfaces

Document Object Reference Manual Python3 Examples

In Python, an abstract class is a special kind of class that cannot be instantiated and can only be inherited. Abstract classes are usually used to define interfaces, that is, a set of method declarations without concrete implementations. Subclasses must implement these methods before they can be instantiated.

Python provides the abc module to create abstract classes. We can use the ABC class and abstractmethod decorator to define abstract methods.

Below is an example of defining an interface with an abstract class:

Example

from

abc

import

ABC

,

abstractmethod

class

Animal

(

ABC

)

:

   

@

abstractmethod

   

def

make_sound

(

self

)

:

       

pass

   

@

abstractmethod

   

def

move

(

self

)

:

       

pass

class

Dog

(

Animal

)

:

   

def

make_sound

(

self

)

:

       

return

"Woof!"

   

def

move

(

self

)

:

       

return

"Running on four legs"

class

Bird

(

Animal

)

:

   

def

make_sound

(

self

)

:

       

return

"Chirp!"

   

def

move

(

self

)

:

       

return

"Flying in the sky"

Instantiate the subclasses

dog

=

Dog

(

)

bird

=

Bird

(

)

print

(

dog.

make_sound

(

)

)

 

Output: Woof!

print

(

dog.

move

(

)

)

       

Output: Running on four legs

print

(

bird.

make_sound

(

)

)

Output: Chirp!

print

(

bird.

move

(

)

)

     

Output: Flying in the sky

Code analysis:

  1. Animal is an abstract class that inherits from ABC. It defines two abstract methods make_sound and move, and these methods have no concrete implementation.
  2. Dog and Bird Is Animal 's subclasses, and they must implement the make_sound and move method, otherwise they will throw TypeError。
  3. Dog class implements the make_sound method returning "Woof!", and implements the move method returning "Running on four legs".
  4. Bird class implements the make_sound method returning "Chirp!", and implements the move method returning "Flying in the sky".
  5. Finally, we instantiated the Dog and Bird classes and called their methods.

Output result:

Woof!
Running on four legs
Chirp!
Flying in the sky

Document Object Reference Manual Python3 Examples