Conflicting needs for __init__ method
dickinsm at gmail.com
Tue Jan 16 16:25:08 CET 2007
On Jan 15, 4:54 pm, Ben Finney <bignose+hates-s... at benfinney.id.au>
> dicki... at gmail.com writes:
> > Suppose you're writing a class "Rational" for rational numbers. The
> > __init__ function of such a class has two quite different roles to
> > play.
> That should be your first clue to question whether you're actually
> needing separate functions, rather than trying to force one function
> to do many different things.
Agreed. It was clear that I wanted two separate functions, but it
seemed that the system was effectively forcing me to use just one;
that is, I was working from the following two assumptions:
(1) *Every* time a Rational is created, __init__ must eventually be
(2) The user of the class expects to call Rational() to create
(1) argues for __init__ being small, simple and efficient, while (2)
wants it to be large and user friendly (possibly dispatching to other
methods to do most of the real work). But as has been pointed out,
thanks to the existence of __new__, (1) is simply false. Time to be
thankful for new-style classes.
> > But __init__ also plays another role: it's going to be used by the
> > other Rational arithmetic methods, like __add__ and __mul__, to
> > return new Rational instances.
> No, it won't; those methods won't "use" the __init__ method. They will
> use a constructor, and __init__ is not a constructor (though it does
> get *called by* the construction process).
Sorry---I'm well aware that __init__ isn't a constructor; I wasn't
being precise enough in my use of `used'.
More information about the Python-list