Returning another instance from constructor

From: Edward Diener (eldiener_at_earthlink.net)
Date: 07/31/04


Date: Sat, 31 Jul 2004 02:03:49 GMT

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.



Relevant Pages

  • Re: Using metaclassed to dynamically generate a class based on a parameter to the objects init funct
    ... but when mucking around with metaclasses it's important be precise ... I highly recommend you consider whether features like instance methods ... constructor of the new subclass, then return an object created from ... creates its subclass directly from the metaclass's constructor. ...
    (comp.lang.python)
  • Re: initializing mutable class attributes
    ... I need to understand the 'WHY' behind a design ... satisfied with an explanation of "that's the Python way and you just have to ... the design of a language can make a very good language. ... default constructor and a non-default one at the same time. ...
    (comp.lang.python)
  • Re: Trying to understand Python objects
    ... the way it describes the way objects work with Python. ... One convention that you seem to be unaware of is that assigning ... initialisation method) so that each instance has a separate attribute ... When you create a new instance of a class, its constructor is called ...
    (comp.lang.python)
  • Re: initializing mutable class attributes
    ... I've done my share of Python teaching, ... that is probably a mistake ... I may not have enough experience with beginners, I guess -- my wife, ... have such a constructor, C++'s and Java's rules are nothing BUT overhead ...
    (comp.lang.python)
  • Re: __init__ explanation please
    ... Yes, that is correct, although I too have been known to use "constructor" ... The following class does not call the initializer: ... Under the hood, Python does something ... DUCK TYPING: If it looks like a duck, walks like a duck, and quacks like ...
    (comp.lang.python)