Custom Meta-Classes
Understand creating custom metaclasses in detail.
We'll cover the following...
We'll cover the following...
In this section, we’ll create a metaclass without type(). To create a custom metaclass we have to inherit type metaclass and override __init__() and __new__().
Overriding the methods
Before overriding the methods, let’s first get an overview on their functionality.
- 
__new__: It creates a new object and returns it. Before the control goes to__init__(),__new__()is called.
- 
__init__: It initializes the created object.
Example
Let’s code an example.
Python 3.10.4
# Defining a classclass A:pass# Defining our own new methoddef new(cls):x = object.__new__(cls)x.attr = 1return x# override __new__() methodA.__new__ = new# Making an object and testingobj = A()print(obj.attr)
In the above example, you can see that we make an empty class with no namespace. Then, we define a class method ...