In metaclass, when to use __new__ vs. __init__?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Matthew Wilson

    In metaclass, when to use __new__ vs. __init__?

    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

    --
    Programming, life in Cleveland, growing vegetables, other stuff.

  • bruno.desthuilliers@gmail.com

    #2
    Re: In metaclass, when to use __new__ vs. __init__?

    On 12 mai, 18:10, Matthew Wilson <m...@tplus1.co mwrote:
    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__.

    Comment

    Working...