singleton ... again

Asaf Las roegltd at gmail.com
Wed Feb 12 05:34:37 CET 2014


playing a bit with subject. 

pros and cons of this approach? did i create bicycle again? :-)

class myclass(object):
    class_instance = None
    
    def __new__(cls, *args, **kwargs):
        if myclass.class_instance == None:
            return object.__new__(cls)
        return myclass.class_instance

    def __init__(self, some):
        if self.__class__.class_instance == None: # init blocker 
            self.__class__.class_instance = self
            self.member = some
    
    def __del__(self):
        self.__class__.class_instance = None
    
one_class = myclass(1)
print(id(one_class), one_class.member )

two_class = myclass(2)
print(id(two_class), two_class.member)




More information about the Python-list mailing list