什么时候在python中使用Singleton? [英] When to use a Singleton in python?

查看:218
本文介绍了什么时候在python中使用Singleton?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有很多问题与在python中使用Singleton模式有关,尽管该问题可能重复了已经讨论的许多方面,但是我没有找到以下特定问题的答案.

There are many questions related to the use of the Singleton pattern in python, and although this question might repeat many of the aspects already discussed, I have not found the answer to the following specific question.

假设我有一个类MyClass,我只想实例化一次.在python中,我可以在代码myclass.py中执行以下操作:

Let's assume I have a class MyClass which I want to instantiate only exactly once. In python I can do this as follows in the code myclass.py:

class MyClass(object): 
    def foo(self):
        ....


instance = MyClass()

然后在任何其他程序中,我都可以简单地用

Then in any other program I can refer to the instance simply with

import myclass
myclass.instance.foo()

在什么情况下此方法足够?在什么情况下使用Singleton模式有用/强制?

Under what circumstances is this approach enough? Under what circumstances is the use of a Singleton pattern useful/mandatory?

推荐答案

单例模式通常是为了方便而不是要求. Python与其他语言有点不同,与其他语言相比,它很容易在测试中模拟单例(只是破坏全局变量!),但是在创建单例时问自己并不是一个好主意:我是为了方便起见还是因为只有一个实例是绝对必要的?将来可能不止一个吗?

The singleton pattern is more often a matter of convenience than of requirement. Python is a little bit different than other languages in that it is fairly easy to mock out singletons in testing (just clobber the global variable!) by comparison to other languages, but it is neverthess a good idea to ask yourself when creating a singleton: am I doing this for the sake of convenience or because it is stricly necessary that there is only one instance? Is it possible that there may be more than one in the future?

如果您创建的类实际上只会被构造一次,则使状态成为模块的一部分并将其方法转换为模块级别的函数可能更有意义.如果将来可能只改变一个实例的假设,那么传递单例实例通常要好得多,而不是通过全局名称引用单例.

If you create a class that really will be only constructed once, it may make more sense to make the state a part of the module, and to make its methods into module-level functions. If there is a possibility that the assumption of exactly one instance may change in the future, then it is often much better to pass the singleton instance around rather than referencing the singleton through a global name.

例如,您可以通过以下方式轻松实现单例":

For example, you can just as easily implement a "singleton" this way:

if __name__ == '__main__':
   instance = MyClass()
   doSomethingWith(instance)

在上面的示例中,实例"是单例的,因为它仅被构造一次,但是处理该实例的代码是提供实例的,而不是引用module.instance的,这使得重用部分实例更为容易.代码,如果在将来的某些情况下您需要多个MyClass.

In the above, "instance" is singleton by virtue of the fact that it is constructed only once, but the code that handles it is provided the instance rather than referencing module.instance, which makes it easier to reuse pieces of the code if, in some future situation, you need more than one MyClass.

这篇关于什么时候在python中使用Singleton?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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