Returning another instance from constructor

E

Edward Diener

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.
 
D

Dan Sommers

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.

Regards,
Dan
 
E

Edward Diener

Dan said:
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 ?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,754
Messages
2,569,521
Members
44,995
Latest member
PinupduzSap

Latest Threads

Top