__init__ is the initialiser

Chris Angelico rosuav at gmail.com
Fri Jan 31 15:28:28 EST 2014


On Sat, Feb 1, 2014 at 7:17 AM, Mark Lawrence <breamoreboy at yahoo.co.uk> wrote:
> To clarify the situation I think we should call __new__ "the thing that
> instanciates an instance of a class" and __init__ "the thing that isn't
> actually needed as you can add attributes to an instance anywhere in your
> code" :)

With a typical class layout, you have something like this:

class Foo:
    def __init__(self, some, other, args):
        self.stuff=some+other, other+args
    def roll(self, arg):
        ret,keep=self.stuff
        self.stuff=keep,arg
        return ret

This has an invariant: it always has a two-item tuple in self.stuff.
The job of __init__ is to get the class invariants straight. Before
it's called, you can't safely call anything else, because all those
other parts of the class are written on the assumption that __init__
will be called first. This is a fairly common way of laying out a
class, and it fits pretty much any language.

So what is __new__ and what is __init__? The former is the thing you
rarely need, and when you do, you can go fiddle with the docs if
necessary; the latter is the most obvious place to guarantee
invariants. Whatever you call them, they'll both be called before
pretty much anything else in the class is, barring weirdnesses, which
is something you cannot depend on with other methods. Yes, you can add
attributes anywhere, but you shouldn't need this:

f = Foo()
f.setup(12,23,34)

Instead, use this:

f = Foo(12,23,34)

And then there's no way to accidentally muck something up and have a
Foo that breaks its invariants.

ChrisA



More information about the Python-list mailing list