在这个 Singleton 装饰器实现中,__init__ 何时被调用,它究竟做了什么?

In this Singleton decorator implementation, when is the __init__ called, and what exactly does it do?

在下面的Singleton实现中,Singletonclass中有一个__init__。 是什么触发了它,它在幕后做了什么?

class Singleton:

    def __init__(self, cls):
        self._cls = cls

    def Instance(self):
        try:
            return self._instance
        except AttributeError:
            self._instance = self._cls()
            return self._instance

    def __call__(self):
        raise TypeError('Singletons must be accessed through `Instance()`.')

    def __instancecheck__(self, inst):
        return isinstance(inst, self._cls)
@Singleton
class DBConnection(object):

    def __init__(self):
        """Initialize your database connection here."""
        pass

    def __str__(self):
        return 'Database connection object'
c1 = DBConnection.Instance()
c2 = DBConnection.Instance()

print("Id of c1 : {}".format(str(id(c1))))
print("Id of c2 : {}".format(str(id(c1))))

print("c1 is c2 ? " + str(c1 is c2))

最后一个代码块的输出是:

Id of c1 : 139699882512960
Id of c2 : 139699882512960
c1 is c2 ? True

这些行:

@Singleton
class DBConnection(object):

相当于:

class DBConnection(object):
    # rest of class elided
DBConnection = Singleton(DBConnection)

所以你可以从上面的最后一行看到 Singleton 像一个函数一样被调用,这就是你如何实例化一个 class,也就是 __init__() 被调用的时候。