In metaclass, when to use __new__ vs. __init__?

Discussion in 'Python' started by Matthew Wilson, May 12, 2008.

  1. 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.
    http://blog.tplus1.com
    Matthew Wilson, May 12, 2008
    #1
    1. Advertising

  2. Matthew Wilson

    Guest

    On 12 mai, 18:10, Matthew Wilson <> 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__.
    , May 12, 2008
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. chenyu
    Replies:
    1
    Views:
    725
    Alex Martelli
    Nov 7, 2003
  2. Jp Calderone
    Replies:
    2
    Views:
    303
    Alex Martelli
    Nov 10, 2003
  3. Felix Wiemann
    Replies:
    9
    Views:
    379
    Martin
    Feb 16, 2005
  4. Steven Bethard
    Replies:
    2
    Views:
    439
    Steven Bethard
    Feb 16, 2005
  5. Peter Cacioppi

    when to use __new__, when to use __init__

    Peter Cacioppi, Oct 14, 2013, in forum: Python
    Replies:
    1
    Views:
    119
    Ethan Furman
    Oct 15, 2013
Loading...

Share This Page