Hello,
I have a type (say: T) which normally receives as main init argument an object
that can be of any other type. Occasionally, this arg object may precisely be
of type T. In this case, for several reasons, I wish not to "over-instanciate",
rather that the constructor returns the source object unchanged. I did some
research and trials on the topic, and found as sole solution to overload
__new__ as shown below. Still, as said in the doc, __init__ was not skipped
(what for?), I need to do it myself. The following example seems to work. I
have 3 questions:
* Is there anything I should pay attention to?
* Why, then, is __init__ still executed when the instanciated object is
'manually' returned? What's the use of that feature?
* I find this an ugly distorsive practice. Isn't there a more graceful way not
to instanciate? Or to simply return the desired object without caring of
side-effects? Or am I so far to undestand what's up that I would better stop
typing?
denis
class T(object):
def __new__(self,source):
print "_new_ -- source: %s:%s" %(source.__class__,source)
if source.__class__ == T:
print "source is T object"
return source
print "new T object instanciated"
return object.__new__(T,self,source)
def __init__(self,source):
print "_init_ -- source: %s:%s" %(source.__class__,source)
if source.__class__ != T:
print "def attribs"
self.typ = source.__class__.__name__
self.dat = source
def __repr__(self):
return "<%s>:%s" %(self.typ,self.dat)
x = "xxx"
t = T(x)
tt = T(t)
print "x=%s t=%s tt=%s" %(x,t,tt)
===>>
_new_ -- source: <type 'str'>:xxx
new T object instanciated
_init_ -- source: <type 'str'>:xxx
def attribs
_new_ -- source: <class '__main__.T'>:<str>:xxx
source is T object
_init_ -- source: <class '__main__.T'>:<str>:xxx
x=xxx t=<str>:xxx tt=<str>:xxx
_______________________________________________
Tutor maillist - Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor