In metaclass, when to use __new__ vs. __init__?

bruno.desthuilliers at gmail.com bruno.desthuilliers at gmail.com
Mon May 12 12:57:34 EDT 2008


On 12 mai, 18:10, Matthew Wilson <m... at tplus1.com> wrote:
> I have been experimenting with metaclasses lately.  It seems possible to
> define a metaclass by either subclassing type and then either redefining
> __init__ or __new__.
>
> Here's the signature for __init__:
>
>     def __init__(cls, name, bases, d):
>
> and here's __new__:
>
>     def __new__(meta, classname, bases, d):
>
> Every metaclass I have found monkeys with d, which is available in both
> methods.  So when is it better to use one vs the other?

Well... The __new__ method is responsible for creating and returning a
new  instance (so in this case, a new class), which is then passed to
the __init__ method. So which one you want to use depends on what you
want to do. If you only want to add some attributes/methods, register
either the class or some of it's methods somewhere etc, then __init__
is fine. If you have to transform / replace / whatever some of the
(not yet) attributes, fiddle with the inheritance tree, cache the
class object or such things, you'd better do it in __new__.



More information about the Python-list mailing list