Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

implement singleton with metaclass

the code below is how i implement singleton with metaclass, and it works well

class Test_MetaClass(type):

    def __init__(cls, name, bases, dict):
        super(Test_MetaClass, cls).__init__(cls, bases, dict)
        cls._instance = None
        print 'Test_MetaClass __init__'

    def __call__(cls, *args, **kwargs):
        if cls._instance is None:
            cls._instance = super(Test_MetaClass, cls).__call__(*args, **kwargs)
        print 'Test_MetaClass __call__'
        return cls._instance


class A(object):
    __metaclass__ = Test_MetaClass
    def __init__(self):
        print 'A __init__ triggered'

a = A()
b = A()

output:

Test_MetaClass __init__
A __init__ triggered
Test_MetaClass __call__
Test_MetaClass __call__

my question is why b = A() straight go to Test_MetaClass.__call__ and ignore __init__ ?

like image 706
limboy Avatar asked Nov 04 '22 17:11

limboy


1 Answers

Isn't that what you wanted? cls._instance isn't None, so it won't execute type.__call__(cls, *args, **kwargs):

>>> type.__call__(A)
A __init__ triggered
<__main__.A object at 0x00BADB30>

It's through this call that A.__new__ and A.__init__ get called to create/initialize a new instance. But for your singleton you only want one instance.

like image 187
Eryk Sun Avatar answered Nov 15 '22 09:11

Eryk Sun