Returning another instance from constructor

Edward Diener eldiener at earthlink.net
Fri Jul 30 22:03:49 EDT 2004


Is there a way in Python to have the constructor of a class "return" another
instance of the same class ? I am well aware of the fact that __init__ does
not return anything, but I would love to do something like this:

class X(object):
    def __init__(self,...other parameters):
        # some magic code

x = X()
y = X()

and have y actually referencing x automatically.

Of course I am aware that if X is passed an optional parameter of type X in
its constructor, it can forward all its member functions to that other X.
But I am looking for something even more magical. I thought that maybe I
could do such magic using metaclasses, but metaclasses only create classes
and not class instances, so I do not see how. If anyone has any ideas I
would love to hear it.





More information about the Python-list mailing list