How to Implement an Abstract Base Class with Metaclass
In this tutorial, you will learn how to create a class that uses the metaclass mechanism in Python to define a class. In other words, you will create a class that creates another class. You will do this by implementing the abstract base class, which acts as the blueprint for the class that you will eventually create. We will implement the abstract base class as a metaclass, which will allow us to reuse the code from the abstract base class when creating the final class.
An abstract base class is a type that serves as a template for other classes. Abstract base classes are an excellent concept in Python since they enable you to create a common mold for other classes.
An abstract base class is “Abstract” because it is non-existent – it’s just an ideal way for some other class to exist, but it cannot exist on its own.
Here is the Python Program for Abstract Base Class with MetaClass
import inspect
class MyABC(type):
def init (class_object, *args):
#print('Meta. init ')
#print(class_object)
#print(args)
# ('Base',
# (<type 'object'>,),
# {
# ' required_methods ': ['foo', 'bar'],
# ' module ': ' main ',
' metaclass ': <class ' main .MyABC'>
# })
# attr = dict(args)
if not ' metaclass ' in args[2]:
return
if not ' required_methods ' in args[2]:
raise Exception("No required_methods ")
name = args[0]
required_methods = set(args[2] [' required_methods '])
def my_init(self, *args, **kwargs):
if self. class . name == name:
raise Exception("You are required to subclass the '{}' class"
.format(name))
#print("my_init")
methods = set([ x[0] for x in
inspect.getmembers(self. class , predicate=inspect.ismethod)])
if not required_methods.issubset( methods ):
missing = required_methods - methods
raise Exception("Requried method '{}' is not implemented in '{}'"
.format(', '.join(missing), self. class . name ))
class_object. init = my_init
class Base(object):
metaclass = MyABC
required_methods = ['foo', 'bar']
# b = Base() # Exception: You are required to subclass the 'Base' class
class Real(Base):
def foo():
pass
def bar():
pass
r = Real()
class Fake(Base):
def foo():
pass
#f = Fake() # Exception: Requried method 'bar' is not implemented in class 'Fake'
class UnFake(Fake):
def bar():
pass
uf = UnFake()