[Tutor] my __new__ not getting called before __init__

Karthik Gurumurthy karthikg@aztec.soft.net
Wed, 26 Dec 2001 16:34:54 +0530


Is something wrong with this code?
when i run it using python2.2 Singleton's __init__ is getting called
and not HoldThis's __init__.

http://www.python.org/2.2/descrintro.html

says the __new__ is always called before __init__.

thanks,
karthik.

<code>
class HoldThis:
    def __init__(self,arg):
        print "KeepThis called with " + arg
        self.val = arg
    def func(self):
        print self.val
        
class Singleton:
    __instance=None

    def __init__(self,arg):
        print "Singleton called"
    def __new__(cls,arg):
        print "__new__ called"
        if not Singleton.__instance:
            Singleton.__instance = HoldThis(arg)
        else:
            Singleton.__instance.val = arg
        return Singleton.__instance
    def __getattr__(self,name):
        return getattr(Singleton.__instance,name)
    def __setattr__(self,name,value):
        setattr(Singleton.__instance,name,value)

</code>