Suppose we have a program that deals with animals, and de decide to have Abstract Class that defines common features of every animal, such as walking:
from abc import ABC
class Animal(ABC):
def __init__(self, name):
self.name = name
def walk(self):
print(f"{self.name} is walking")We can then create a Cat that inherits from this class:
from abc import ABC
class Animal(ABC):
def __init__(self, name):
self.name = name
def walk(self):
print(f"{self.name} is walking")
class Cat(Animal):
def __init__(self, name):
super().__init__(name)
def purr(self):
print(f"{self.name} is purring")
manuel = Cat("manuel")
manuel.walk()
> "manuel is walking"
manuel.purr()
> "manuel is purring"In the code above we instantiated a Cat called “manuel” who inherited all the traits of Animal, as well as a Cat-specific method called purr.
The next step is, for example, to define how the Animals talk. Since each animal talks differently (in this contrived example, we instantiate Talking as an interface):
from abc import ABC, abstracmethod
class Animal(ABC):
def __init__(self, name):
self.name = name
def walk(self):
print(f"{self.name} is walking")
class Talking(ABC):
@abstractmethod
def talk(self):
...
class Cat(Animal):
def __init__(self, name):
super().__init__(name)
def purr(self):
print(f"{self.name} is purring")
class Dog(Animal, Talking)
def talk(self):
print(f"{self.name} is talking)
manuel = Cat("manuel")
manuel.walk()
> "manuel is walking"
manuel.purr()
> "manuel is purring"
theo = Dog("theo")
theo.talk()
> "theo is talking"By creating another class with an abstract method we are unable to instantiate it directly. In this case, the Talking class is the interface we are creating to ensure that this particular instance of Dog can talk
Note
To create a truly abstract class, the class definition must inherit from
ABCand must implement at least one abstract method.