【问题标题】:In this Singleton decorator implementation, when is the __init__ called, and what exactly does it do?在这个 Singleton 装饰器实现中,何时调用 __init__ ,它究竟做了什么?
【发布时间】:2020-03-03 16:42:30
【问题描述】:

在下面的 Singleton 实现中,Singleton 类中有一个__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

【问题讨论】:

    标签: python singleton decorator init


    【解决方案1】:

    这些行:

    @Singleton
    class DBConnection(object):
    

    相当于:

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

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

    【讨论】:

      猜你喜欢
      • 2021-08-22
      • 2017-06-11
      • 2016-08-10
      • 2011-06-18
      • 2012-07-23
      • 2016-09-10
      • 2023-03-15
      • 2012-10-17
      • 2021-06-04
      相关资源
      最近更新 更多