Singleton class and __new__




Initialization of class to single object is called singleton class
Eventough if you create many object of singleton class first created object will be returned

How to achive singleton in python ?
Before stepping in to Create Singleton class

About __new__

__new__ When you need to control the creation of a new instance
or to execute something before __init__ executes.
__new__ will be called before __init__
__new__ gets class as first argument
__new__ returns instance of class
__new__ is static class method

What experts says about __new__ ?
Use __new__ unless you're subclassing an immutable type like str, int, unicode or tuple.

If __new__() does not return an instance of cls, then the new instance's __init__() method will not be invoked
yoiu will endup with error AttributeError: 'NoneType' object has no attribute 'init_check'

About __init__

__init__ doesn't return anything
__init__ when you need to control initialization
__init__ takes self as parameter



class Single(object):
    """ Singleton class of new style class
        which inherits object
    """
    instance = None

    def __new__(clas, *args, **kwargs):

        if clas.instance is not None:
            #return already existing Instance
            return clas.instance
        else:
            #no instance exists create new one
            #clas.instance = object.__new__(clas, *args, **kwargs)
            super(Single, self).__new__()  
            return clas.instance

    def __init__(self):
        self.init_check = "Init successfull"

    def method(self):
        print "Method Successfull"



if __name__ == "__main__":
    x = Single()
    print "id x : ",id(x)
    y = Single()
    print "id y : ",id(y)
    print "--- init check ---"
    print y.init_check
    print "--- method check ---"
    y.method()


Output :
id x : 3076941132
id y : 3076941132
--- init check ---
Init successfull
--- method check ---
Method Successfull

In python id(object) Returns the identity of an object. This is guaranteed to be unique among
simultaneously existing objects.

In the output id(x) and id(y) are returning same object 3076941132 singleton achived :)