super(type,subclass) in simple singleton implementation

Posted by Tianchen Wu on Stack Overflow See other posts from Stack Overflow or by Tianchen Wu
Published on 2014-06-12T21:09:50Z Indexed on 2014/06/12 21:25 UTC
Read the original article Hit count: 185

Filed under:

when I was implementing naive singleton in python, I came up with a problem with super key word. As usual the behavior of super is always tricky and buggy, hope someone can shed light on it. Thanks :)

The problem is that:

class Singleton(object):
    def __new__(cls,*args,**kw):
        if not hasattr(cls,'_instance'):
            #create a instance of type cls,
            origin=super(Singleton,Singleton).__new__(cls,*args,**kw)
            cls._instance=origin
        return cls._instance

class B(Singleton):
    def __init__(self,b):
        self.b=b

It actually works, but I am wondering

Will it be better if I change line 5 to the below, like in most of the books?

origin=super(Singleton,cls).__new__(cls,*args,**ks)

what's the difference to make?

© Stack Overflow or respective owner

Related posts about python