Abstract Base Class with metaclass – Python Programming

CWC
6 Min Read
Abstract Base Class with metaclass - Python Programming

Python is a programming language with lots of features and one of the best feature is its abstraction power. This means that when you are creating objects then you don’t need to write the same code repeatedly for each object. Instead you can write a single piece of code that can be used to create multiple types of objects. The abstraction power of python can be explained through the example below.

Abstract base class (ABC) is a concept in Python programming that is very important for creating a generic class that can be used in any context. Abstract base classes are the parent classes of all classes in Python. Abstract base classes are also called as metaclasses.

What is metaclass?

Metaclasses are the superclass of classes in Python. A metaclass is a class that is the superclass of all classes. You can understand the concept of metaclass in a very simple way. If you take an example of a car and you ask what is the vehicle, you will get an answer as a car. Now, if you want to get the answer as a car, then you can call it as a metaclass.

ABCs are also known as metaclasses in Python programming. The class of metaclasses are ABCs and are the parent classes of all classes in Python. You can create a class named as a metaclass by using ABC. ABC is an abstract base class.

Abstract Base Class with metaclass – Python Programming

How to create a metaclass?

To create a metaclass, you will need to create a class that inherits from ABC. You will have to define a new __metaclass__ attribute that will be inherited by the class.

The following code shows you how to create a metaclass:


from abc import ABCMeta
class A(object):
__metaclass__ = ABCMeta
def __init__(self):
pass
class B(A):
def __init__(self):
print('Hello')
class C(B):
def __init__(self):
print('Goodbye')
a = A()
b = B()
c = C()
print('Type of a', type(a))
print('Type of b', type(b))
print('Type of c', type(c))
print()

In the above example, we will be creating a class named as A. This class is the parent class of all classes in Python. The class named as A will have a attribute named as __metaclass__ that will inherit all the attributes of ABC.

You will notice that we have created a class named as B that inherits from A. We have also created a class named as C that inherits from B.

Let us see what happens when we create an instance of the class C.

In the above example, we will be creating an instance of the class C. We will be getting an instance of the class C and you will notice that the instance of the class C inherits the attributes of ABC.

Now, if you check the type of the variable a, it will be <class ‘__main__.a’=””>

Python Program: 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()

Share This Article
Leave a comment

Leave a Reply

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

English
Exit mobile version