Python,使用单例模式或仅全局变量 [英] Python, using singleton pattern or just global variable

查看:385
本文介绍了Python,使用单例模式或仅全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在python中,使用单例模式而不是使用全局变量更好吗?

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.

推荐答案

全局变量方法的问题在于,您始终可以访问该变量并修改其内容,因此它将是Singleton的较弱"形式图案.另外,如果您有一个以上的Singleton类,则必须为每个类定义一个函数和一个全局变量,这样它最终会比模式更混乱.

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.

这篇关于Python,使用单例模式或仅全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆