Python Program: Abstract Base Class without abc

2 Min Read
Python Program to Alter Iterator

As mentioned in the last post, you can use the abc module to create a base class that has all of the methods in Python, such as print. This is helpful because there are some common functions that are used often and you don’t have to define them in every class you create. To create a base class, you can use the abstract keyword followed by the base class name, followed by parentheses. In this post I will show you how we can write Python program with abstract base class without abc.

Python Program: Abstract Base Class without abc

import inspect

class Base():
def 	init 	(self, *args, **kwargs):
if self. 	class 	. 	name 	== 'Base':
raise Exception('You are required to subclass the {} class'

methods = set([ x[0] for x in
inspect.getmembers(self. 	class 	, predicate=inspect.ismethod)])
required = set(['foo', 'bar'])
if not required.issubset( methods ):
missing = required - methods
raise Exception("Requried method '{}' is not implemented in '{}'"
.format(', '.join(missing), self. 	class 	. 	name 	))

class Real(Base):
def foo(self):
print('foo in Real')
def bar(self):
print('bar in Real')
def other(self):

class Fake(Base):
# user can hide the 	init 	method of the parent class:
# def 	init 	(self):
# pass
def foo(self):
print('foo in Fake')

r = Real()
#b = Base()	# You are required to subclass the Base class
#f = Fake()	# Requried method 'bar' is not implemented in class 'Fake'

Share This Article
Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *

Exit mobile version