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

后端 未结 6 2101
被撕碎了的回忆
被撕碎了的回忆 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:48

    Similar to Sven's "Borg pattern" suggestion, you could just keep all your state data in a class, without creating any instances of the class. This method utilizes new-style classes, I believe.

    This method could even be adapted into the Borg pattern, with the caveat that modifying the state members from the instances of the class would require accessing the __class__ attribute of the instance (instance.__class__.foo = 'z' rather than instance.foo = 'z', though you could also just do stateclass.foo = 'z').

    class State:    # in some versions of Python, may need to be "class State():" or "class State(object):"
        __slots__ = []   # prevents additional attributes from being added to instances and same-named attributes from shadowing the class's attributes
        foo = 'x'
        bar = 'y'
    
        @classmethod
        def work(cls, spam):
            print(cls.foo, spam, cls.bar)
    

    Note that modifications to the class's attributes will be reflected in instances of the class even after instantiation. This includes adding new attributes and removing existing ones, which could have some interesting, possibly useful effects (though I can also see how that might actually cause problems in some cases). Try it out yourself.

提交回复
热议问题