Python singleton pattern

can someone tell me why this is not true as a singleton pattern:

class preSingleton(object):
    def __call__(self):
        return self

singleton = preSingleton()

# singleton is actually the singleton

a = singleton()
b = singleton()

print a==b  

a.var_in_a = 100
b.var_in_b = 'hello'

print a.var_in_b
print b.var_in_a

Edit: The above code prints:

True
hello
100

Many thanks

Part two

Maybe this is better?

class Singleton(object):
    def __new__(cls):
        return cls

a = Singleton()
b = Singleton()

print a == b

a.var_in_a = 100
b.var_in_b = 'hello'

print a.var_in_b
print b.var_in_a

Edit: The above code prints:

True
hello
100

Thanks again.

+3
source share
6 answers

Singletones are actually very simple to make in Python. The trick is for the module to do your encapsulation for you, rather than creating a class.

  • The module will be initialized only once.
  • The module will not be initialized until the first import.
  • Any attempts to re-import the module will return a pointer to the existing import.

And if you want to pretend that the module is an instance of the class, you can do the following

import some_module
class SomeClass(object):
    def __init__(self):
        self.singleton = some_module
+10

. , - .

>>> class preSingleton(object):
...     def __call__(self):
...         return self
...
>>> singleton = preSingleton()
>>> singleton2 = preSingleton()
>>> singleton
<__main__.preSingleton object at 0x00C6D410>
>>> singleton2
<__main__.preSingleton object at 0x00C6D290>
+3

. , .

, - , , , , ...

edit: , Borg, , , , .

+2

, :

def singleton(cls):
    """Decorate a class with @singleton when There Can Be Only One."""
    instance = cls()
    instance.__call__ = lambda: instance
    return instance

:

@singleton
class MySingleton:
    def spam(self):
        print id(self)

, , MySingleton , - . MySingleton() . :

>>> MySingleton
<__main__.MySingleton instance at 0x7f474b9265a8>
>>> MySingleton()
<__main__.MySingleton instance at 0x7f474b9265a8>
>>> MySingleton() is MySingleton
True
>>> MySingleton.spam()
139944187291048
>>> MySingleton().spam()
139944187291048
+2

( , ...). .

, Java (), Python , . , singleton() singleton, .

+1

:

>>> class preSingleton(object):
...     def __call__(self):
...         return self
...
>>> x = preSingleton()
>>> y = preSingleton()
>>> x == y
False

, , Singleton.

0

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


All Articles