Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #65139 > unrolled thread

Re: __init__ is the initialiser

Started byChris Angelico <rosuav@gmail.com>
First post2014-02-01 07:28 +1100
Last post2014-02-01 07:28 +1100
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: __init__ is the initialiser Chris Angelico <rosuav@gmail.com> - 2014-02-01 07:28 +1100

#65139 — Re: __init__ is the initialiser

FromChris Angelico <rosuav@gmail.com>
Date2014-02-01 07:28 +1100
SubjectRe: __init__ is the initialiser
Message-ID<mailman.6219.1391200111.18130.python-list@python.org>
On Sat, Feb 1, 2014 at 7:17 AM, Mark Lawrence <breamoreboy@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

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web