Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > In metaclass, when to use __new__ vs. __init__?

Reply
Thread Tools

In metaclass, when to use __new__ vs. __init__?

 
 
Matthew Wilson
Guest
Posts: n/a
 
      05-12-2008
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
 
Reply With Quote
 
 
 
 
bruno.desthuilliers@gmail.com
Guest
Posts: n/a
 
      05-12-2008
On 12 mai, 18:10, Matthew Wilson <(E-Mail Removed)> 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__.
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
use of __new__ to permit "dynamic" completion within (any?) IDE ? gst Python 10 12-08-2010 03:56 PM
Good idea to use a class as function with __new__? glomde Python 2 05-28-2007 04:42 PM
How to use "__new__"? could ildg Python 5 03-30-2005 03:06 AM
__new__ does not call __init__ as described in descrintro.html (WAS:Can __new__ prevent __init__ from being called?) Steven Bethard Python 2 02-16-2005 06:50 AM
Overriding list.__new__ Michele Simionato Python 1 07-03-2003 09:52 PM



Advertisments