Abstract classes are intended to abstract functionality that will then be implemented in classes that inherit from the abstract class.
The following classes will inherit from the abstract Person class: Intern and Employee
Attempting to create an instance from the abstract Person class will result in a TypeError exception being thrown.
Additionally, not implementing all abstract methods in a child class causes a TypeError exception.
import abc
class Person(abc.ABC):
''' Abstract Person class '''
@abc.abstractmethod
def __init__(self, first, last):
self.first = first
self.last = last
@abc.abstractmethod
def get_full_name(self):
pass
class Employee(Person):
''' Sample Employee class'''
def __init__(self, first, last, salary):
super().__init__(first, last)
self.salary = salary
def get_full_name(self):
return f'{self.__class__.__name__}: {self.first} {self.last}'
class Intern(Person):
'''' Sample Intern class
does not implement the get_full_name() method!
'''
def __init__(self, first, last, mentor):
super().__init__(first, last)
self.mentor = mentor
joe_smith = Person("Joe", "Smith") #TypeError: Can't instantiate abstract class
john_doe = Employee("John", "Doe", 8000) #this code is correct
print(john_doe.get_full_name(), john_doe.salary) #returns: Employee: John Doe 8000
jane_doe = Intern("Jane", "Doe", john_doe) #TypeError: no implementation of get_full_name() method