In metaclass, when to use __new__ vs. __init__?

M

Matthew Wilson

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?

Thanks for the help.

Matt
 
B

bruno.desthuilliers

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__.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top