В этой реализации декоратора Singleton, когда вызывается __init__, и что именно он делает? - PullRequest
0 голосов
/ 03 марта 2020

в приведенной ниже реализации Singleton есть __init__ в классе Singleton. что вызывает его и что он делает за кадром?

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

1 Ответ

1 голос
/ 03 марта 2020

Эти строки:

@Singleton
class DBConnection(object):

эквивалентны:

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

Таким образом, вы можете видеть из последней строки выше, что Singleton вызывается как функция, которая как вы создаете экземпляр класса, когда __init__() вызывается.

...