Returning other instance from __init__

Alex Martelli aleax at mac.com
Thu Mar 15 10:50:44 EDT 2007


Paul Boddie <paul at boddie.org.uk> wrote:
   ...
> > > class C1:
> > >       def __init__(self,xxx):
   ...
> > Use __new__ for such purposes, not __init__.  (You need to make C1
> > newstyle, e.g. inherit from object, to make special method __new__
> > work).
> 
> Call me a traditionalist, but why wouldn't a factory function be good
> enough?

That depends on whether you need name C1 to refer to a class, or not.

If you want name C1 to be usable outside this module as a class (to
subclass it, use with isinstance or issubclass, be available to an IDE's
classbrowser or other means of introspection including pydoc, etc), then
making name C1 refer to a function instead would not work.

> Or perhaps seeing more special methods and decorators just puts me in
> a grumpy mood. ;-) For me, the power of Python is derived from being
> able to do things like making callables "constructors" whilst
> providing some illusion that C1 (in this case) is a class.

For me, OTOH, it's not just smoke and mirrors (or as you say
"illusion"), there's also plenty of real power, and __new__ is part of
that.  (Decorators however are just handy syntax -- they let you avoid
repeating one name three times, and avoiding repetition is a good thing,
but their real power is essentially that of higher-order-functions that
could of course be used with other syntax if need be).


Alex



More information about the Python-list mailing list