__init__ is the initialiser

Roy Smith roy at panix.com
Sat Feb 1 11:17:40 EST 2014


> On 01/02/2014 14:40, Roy Smith wrote:
> > In article <mailman.6275.1391257695.18130.python-list at python.org>,
> >   Ned Batchelder <ned at nedbatchelder.com> wrote:
> >
> >> The existence of __new__ is an
> >> advanced topic that many programmers never encounter.  Taking a quick
> >> scan through some large projects (Django, edX, SQLAlchemy, mako), the
> >> ratio of __new__ implementations to __init__ implementations ranges from
> >> 0% to 1.5%, which falls into "rare" territory for me.
> >
> >  From our own codebase:
> >
> > $ find . -name '*.py' | xargs grep 'def.*__new__' | wc -l
> > 1
> > $ find . -name '*.py' | xargs grep 'def.*__init__' | wc -l
> > 228
> >
> > Doing the same searches over all the .py files in our virtualenv, I get
> > 2830 (__init__) vs. 50 (__new__).

In article <mailman.6280.1391267257.18130.python-list at python.org>,
 Mark Lawrence <breamoreboy at yahoo.co.uk> wrote:

> You could remove all 228 __init__ and still get your code to work by 
> scattering object attributes anywhere you like, something I believe you 
> can't do in C++/Java.

Why not?  Here's a simple C++ program which uses a constructor:

#include <stdio.h>

class Foo {
public:
    int i;

    Foo() : i(42) {}
};

int main(int, char**) {
    Foo foo;
    printf("foo.i = %d\n", foo.i);
}

If I wanted to, I could remove the constructor and still "get my code to 
work by scattering object attributes anywhere I like":

#include <stdio.h>

class Foo {
public:
    int i;
};

int main(int, char**) {
    Foo foo;
    foo.i = 42;
    printf("foo.i = %d\n", foo.i);
}

> I doubt that you could remove the single __new__ and get your code to work.

Perhaps.  Looking at our own code, the one place we use __new__ is in a 
metaclass, which I think pretty well reinforces Ned's assertion that 
__new__ is an advanced topic.



More information about the Python-list mailing list