Returning another instance from constructor

Edward Diener eldiener at earthlink.net
Sat Jul 31 10:41:55 EDT 2004


Robert Brewer wrote:
> Edward Diener 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.
>
> Sounds like you want a Singleton. My first thought was to override
> __new__; that approach (among many others) is covered pretty well at
> http://c2.com/cgi/wiki?PythonSingleton -- JeremyBowers shows how to do
> it with __new__.

Overriding __new__ should do it. I wasn't looking for a singleton, but the
__new__ override achieves what I want.





More information about the Python-list mailing list