Python, using singleton pattern or just global variable

自古美人都是妖i 提交于 2020-02-01 02:49:04

问题


In python, is it better that using the singleton pattern instead of using global variable?

class Singleton(type):
    def __call__(self, *args, **kwargs):
        if 'instance' not in self.__dict__:
            self.instance = super(Singleton, self).__call__(*args, **kwargs)
        return self.instance

or just make a global variable:

SINGLETON_VARIABLE = None
def getSingleton():
    if SINGLETON is None:
        SINGLETON_VARIABLE = SOME_ININ_CLASS()
    return SINGLETON_VARIABLE

Is it necessary to complicate the life to make a singleton pattern? Thank you in advance.


回答1:


The problem with the global variable approach would be that you can always access that variable and modify its content, so it would be a "weaker" form of the Singleton pattern. Also, if you have more than one Singleton class, you have to define a function and a global variable for each, so it ends up being messier than the pattern.



来源:https://stackoverflow.com/questions/25429349/python-using-singleton-pattern-or-just-global-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!