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()
interpretation:¶
now if we try to instantiate Animal class like before, it will fail
In [4]:
dog = Dog(4)
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]:
interpretation:¶
once we implemented get_num_of_legs, everything works fine, and Animal class can't be instantiated