a metaclass is the class of the class. like a class define how an instance
behaves, a metaclass defines how a class behaves. a class is an instance of
a metaclass.
what many people do not realize, though, is that quite literally everything
in python language is an object.
here you can see that a object, which is an instance of MyClass can add to an
integer. we see int really is an object that can be subclassed and extended
just like user-defined classes.
we all know in oop language, the type of objects are instances of classes. so
what’s the type of the class?
what this shows in python, classes are objects, and they are objects of type type.
type is the a metaclass: a class which instantiates classes. all new-style
classes in python are instances of the type metaclass, including type itself.
all class definition process is the process of instantiating type class.
we can learn this from an example:
so we can use the __new__ or __init__ to customer the process of
creating new class. there comes the metaclass in python.
use __init__ or __new__ in metaclass?
__new__ is called for the creation of a new class, while __init__ is
called after the class is created, to perform additional initialization before
the class is handed to the caller.
The primary difference is that when overriding __new__() you can change
things like the ‘name’, ‘bases’ and ‘namespace’ arguments before you call the
super constructor and it will have an effect, but doing the same thing in
__init__() you won’t get any results from the constructor call.
Note that, since the base-class version of __init__() doesn’t make any
modifications, it makes sense to call it first, then perform any additional
operations. In C++ and Java, the base-class constructor must be called as the
first operation in a derived-class constructor, which makes sense because
derived-class constructions can then build upon base-class foundations.
you should prefer to use __init__ instead of __new__ but for you must
have to use __new__.