A class-of-a-class is called MetaClass. The real use of Metaclass is good to know for beginners. All languages don’t support this. But Python supports it since it follows Smalltalk. Here, you will know how to create metaclass and its use cases.
Bonus Topic for Beginners: How to find The Given Class is Metaclass using ‘type’
Below is the list of all sections. Go ahead and click on any of these links to go to that section.
- How to Identify Metaclass
- Why You Need Metaclass
- Ordinary Vs. MetaClass
- Use Cases of MetaClass
- Best Example of Python2 MetaClass
- Best Example of Python3 MetaClass
- Further Reading
How to Identify Metaclass
Example
class Meta(type): pass # The keyword argument is 'type' # so this is the MetaClass class MyClass(metaclass=Meta): pass # This is not MetaClass, since, it has # keyword argument metaclass=Meta class MySubclass(MyClass): pass # This is not MetaClass, is inherited # from MyClass.
Related Posts
Why You Need Metaclass
- You can create MetaClass like any ordinary class
- The Metaclass is called automatically when you call it from another class
Example:
class LittleMeta(type):
def __new__(cls, clsname, superclasses, attributedict):
print("clsname: ", clsname)
print("superclasses: ", superclasses)
print("attributedict: ", attributedict)
return type.__new__(cls, clsname, superclasses, attributedict)
We will use the metaclass "LittleMeta" in the following example:
class S:
pass
class A(S, metaclass=LittleMeta): -> called automatically
pass
a = A()
clsname: A
superclasses: (<class '__main__.S'>,)
attributedict: {'__module__': '__main__', '__qualname__': 'A'}
Ordinary Vs. Metaclass
Python uses the type function to create classes since type is actually a metaclass. The type function is the metaclass that Python uses to create class objects, but you can also create your own metaclasses.
SomeClass = MetaClass()
object = SomeClass()
SomeClass = type('SomeClass', (), {})

Featured
How to Understand Metaclass in Python Step By Step
Use Cases of Metaclass
- logging and profiling
- interface checking
- registering classes at creation time
- automatically adding new methods
- automatic property creation
- proxies
- automatic resource locking/synchronization.
Python2 Metaclass
In Python 2, metaclasses are set by defining the __metaclass__ variable. This variable can be any callable accepting argument, such as name, bases, and dict.
class MyBase (object):
pass
class MyMeta (type):
pass
class MyClass (MyBase):
__metaclass__ = MyMeta
pass
Python3 Metaclass
In Python 3, metaclasses are set using the keyword metaclass.
class MyBase (object):
pass
class MyMeta (type):
pass
class MyClass (MyBase, metaclass=MyMeta):
pass
Resources
Subscribe Today.
You must be logged in to post a comment.