Returning another instance from constructor

Edward Diener eldiener at earthlink.net
Sat Jul 31 22:58:26 EDT 2004


Dan Sommers wrote:
> On Sat, 31 Jul 2004 02:03:49 GMT,
> "Edward Diener" <eldiener at earthlink.net> wrote:
>
>> 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.
>
> The Borg pattern may be useful:
>
>     http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66531
>
> x and y will still be their own objects, but they'll share all of
> their state information.

I am using new style classes and I see:

# here is the new-style Borg (not much more complex then the "old-style")
class Borg(object):
    _state = {}
    def __new__(cls, *p, **k):
        self = object.__new__(cls, *p, **k)
        self.__dict__ = cls._state
        return self

It seems in my case above I need to say for y, when I am able to recognize
that it should actually be the same as x:

        self.__dict__ = x.__dict__

to have y be the same as x. Is this correct ? Also I can find no
documentation in the Python 2.3 docs for __new__ . Can you point me to it ?





More information about the Python-list mailing list