Python: thinking of a module and its variables as a singleton — Clean approach?

后端 未结 6 2092
被撕碎了的回忆
被撕碎了的回忆 2020-12-13 13:21

I\'d like to implement some sort of singleton pattern in my Python program. I was thinking of doing it without using classes; that is, I\'d like to put all the singleton-rel

6条回答
  •  粉色の甜心
    2020-12-13 13:40

    A common alternative to using a module as a singleton is Alex Martelli's Borg pattern:

    class Borg:
        __shared_state = {}
        def __init__(self):
            self.__dict__ = self.__shared_state
        # and whatever else you want in your class -- that's all!
    

    There can be multiple instances of this class, but they all share the same state.

提交回复
热议问题