Returning other instance from __init__ - I need help

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Sat Mar 17 10:53:18 CET 2007


En Fri, 16 Mar 2007 22:05:05 -0300, Paulo da Silva  
<psdasilvaX at esotericaX.ptX> escribió:

> When debugging, I found this is wrong!!!
> Would someone please clarify what do I have to return from
> __new__?

Try this. I used a classmethod for load, it may be easier to subclass.

class C(object):

     def __new__(cls, filename=None, foo=None, bar=None):
         if filename is not None:
             return cls.load(filename)
         inst = super(C, cls).__new__(cls)
         inst.foo = foo
         inst.bar = bar
         return inst

     @classmethod
     def load(cls, filename):
         inst = super(C, cls).__new__(cls)
         inst.foo = "some foo loaded from "+filename
         inst.bar = "some bar loaded from "+filename
         return inst

class D(C):
     @classmethod
     def load(cls, filename):
         inst = super(D, cls).__new__(cls)
         inst.foo = "D foo loaded from "+filename
         inst.bar = "D bar loaded from "+filename
         return inst


c1 = C(foo=1, bar=2)
print "c1=", c1
print "c1.foo=", c1.foo
print "c1.bar=", c1.bar
c2 = C(filename="xxx.txt")
print "c2=", c2
print "c2.foo=", c2.foo
print "c2.bar=", c2.bar

d1 = D(foo=10, bar=20)
print "d1=", d1
print "d1.foo=", d1.foo
print "d1.bar=", d1.bar
d2 = D(filename="yyy.txt")
print "d2=", d2
print "d2.foo=", d2.foo
print "d2.bar=", d2.bar


-- 
Gabriel Genellina




More information about the Python-list mailing list