Python Abstract Classes

Posted on 12/17/2019 in Python OOP

  • Python Abstract Classes
  • @abstractmethod
  • ABC
In [1]:
class Animal:
    def get_num_of_legs(self): pass
    def name(self): pass

class Dog(Animal):
    def __init__(self, num_of_legs):
        self.__num_of_legs = num_of_legs
        
animal = Animal()

interpretation:

We don't want Animal class be instantiated, but the code didn't prevent it now

In [2]:
from abc import ABC, abstractmethod

class Animal(ABC):
    @abstractmethod
    def get_num_of_legs(self): pass
    @abstractmethod
    def name(self): pass

class Dog(Animal):
    def __init__(self, num_of_legs):
        self.__num_of_legs = num_of_legs

interpretation:

Import python bulit-in class ABC, and abstractmethod to make Animal to be Abstract

In [3]:
animal = Animal()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-3-5d44ba9875b7> in <module>
----> 1 animal = Animal()

TypeError: Can't instantiate abstract class Animal with abstract methods get_num_of_legs, name

interpretation:

now if we try to instantiate Animal class like before, it will fail

In [4]:
dog = Dog(4)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-4-9484f36229ef> in <module>
----> 1 dog = Dog(4)

TypeError: Can't instantiate abstract class Dog with abstract methods get_num_of_legs, name

interpretation:

The error message says Can't instantiate abstract class Dog, because we have to provide the implemention for abstract method get_num_of_legs and name

In [5]:
from abc import ABC, abstractmethod

class Animal(ABC):
    @abstractmethod
    def get_num_of_legs(self): pass


class Dog(Animal):
    def __init__(self, num_of_legs):
        self.__num_of_legs = num_of_legs
    
    def get_num_of_legs(self):
        return 4
In [6]:
dog = Dog(4)
dog.get_num_of_legs()
Out[6]:
4

interpretation:

once we implemented get_num_of_legs, everything works fine, and Animal class can't be instantiated