Self-destructive constructor == Singleton?

I have seen several ways to create singletons in Python, but they all have some kind of flaw. I just came up with a way myself, and I would like to know what's wrong with him :).

class Singleton(object):
    def __init__(self, cls, *args, **kwargs):
        self.instance = cls(*args, **kwargs)

        def blocked(doppelganger, *args, **kwargs):
            raise RuntimeError("singleton")

        cls.__init__ = blocked

    def getInstance(self):
        return self.instance


class A(object):
    def __init__(self, x):
        self.x = x


a = Singleton(A, 10)

This works by passing a class Singleton, which then instantiates, then pushes it, causing its constructor to raise an exception at runtime. The main drawback that I see is that this template will prevent the creation of more instances, but does not guarantee that there is only one instance. It can also forge any class at all, which is probably bad.

, , . , blocked self.__init__ A. A , - -, .

?

+4
1

:

class Singleton(object):
    def __init__(self, cls, *args, **kwargs):
        self.instance = cls(*args, **kwargs)

        def blocked(doppelganger, *args, **kwargs):
            raise RuntimeError("singleton")

        cls.__init__ = blocked

    def getInstance(self):
        return self.instance


class A(object):
    def __init__(self, x):
        self.x = x


class B(A):
    def __init__(self, x, y):
        super(B, self).__init__(x)
        self.y = y


a = Singleton(A, 10)
b = Singleton(B, 10, 20)  # Raises RuntimeError

: Singleton(B, 10, 20) A.__init__, .

. ", . A - , ".

:

b = Singleton(B, 10, 20)
a = Singleton(A, 10)

.

+1

Source: https://habr.com/ru/post/1568403/


All Articles