no return values for __init__ ??

Neil Schemenauer nascheme at enme.ucalgary.ca
Sun Jan 9 18:20:03 EST 2000


Helge Hess <helge.hess at mdlink.de> wrote:
>Hi there,
>
>recently I was heavily wondering why __init__ does not allow return
>values ! Is there any special reason not to do this ?

I would say that it is conceptually wrong.  By the time the
__init__ method is called a new instance has already been
created.  You are proposing that if __init__ returns a value then
this instance should be thrown away.  Any initalizations you do
within __init__ would also be discarded.

A factory function achieves what you want and can do other cool
things too.  If you don't want to use a factory function then
a meta class is probably the best solution (although my head
explodes everything I try to figure them out).

>For example consider this
>  
>  C_singleton = None
>  
>  class C:
>    def __init__(self):
>      if C_singleton is None:
>        c_singleton = self
>      return C_singleton
>
>  c1 = C()
>  c2 = C()
>  'if c1 is c2' will be true


    class Singleton:
        def __init__(self, klass):
            self.klass = klass
            self.instance = None

        def __call__(self, *args, **kw):
            if self.instance is None:
                self.instance = apply(self.klass, args, kw)
            return self.instance

    class RealC:
        pass

    C = Singleton(RealC)

If renaming the class C to something else causes you problems
then you should probably rethink your design.


    Neil

--
"God, root, what is difference?" - Pitr| nascheme at enme.ucalgary.ca
"God is more forgiving." - Dave Aronson| http://www.ucalgary.ca/~nascheme



More information about the Python-list mailing list