data validation when creating an object

Ben Finney ben+python at benfinney.id.au
Wed Jan 15 23:53:56 EST 2014


Roy Smith <roy at panix.com> writes:

>  Ben Finney <ben+python at benfinney.id.au> wrote:
>
> > Who says it's frowned on to do work in the initialiser? Where are they
> > saying it? That seems over-broad, I'd like to read the context of that
> > advice.
>
> There are some people who advocate that C++ constructors should not do
> a lot of work and/or should be incapable of throwing exceptions. The
> pros and cons of that argument are largely C++ specific. […]
>
> But, Python is not C++. I suspect the people who argue for __init__()
> not doing much are extrapolating a C++ pattern to other languages
> without fully understanding the reason why.

Even simpler: They are mistaken in what the constructor is named, in
Python.

Python classes have the constructor, ‘__new__’. I would agree with
advice not to do anything but allocate the resources for a new instance
in the constructor.

Indeed, the constructor from ‘object’ does a good enough job that the
vast majority of Python classes never need a custom constructor at all.

(This is probably why many beginning programmers are confused about what
the constructor is called: They've never seen a class with its own
constructor!)

Python instances have an initialiser, ‘__init__’. That function is for
setting up the specific instance for later use. This is commonly
over-ridden and many classes define a custom initialiser, which normally
does some amount of work.

I don't think ‘__init__’ is subject to the conventions of a constructor,
because *‘__init__’ is not a constructor*.

-- 
 \        “Absurdity, n. A statement or belief manifestly inconsistent |
  `\            with one's own opinion.” —Ambrose Bierce, _The Devil's |
_o__)                                                Dictionary_, 1906 |
Ben Finney




More information about the Python-list mailing list