本文介绍了有没有简单,优雅的方式来定义单身人士?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎有很多方法可以在Python中定义。堆栈溢出有一个共识吗?

There seem to be many ways to define singletons in Python. Is there a consensus opinion on Stack Overflow?

推荐答案

我没有真正看到需要,作为一个功能模块(而不是一个班级)将作为一个单身人士。它的所有变量将被绑定到模块,无法反复实例化。

I don't really see the need, as a module with functions (and not a class) would serve well as a singleton. All its variables would be bound to the module, which could not be instantiated repeatedly anyway.

如果您希望使用类,则无法在Python中创建私有类或私有构造函数,因此您无法保护多个实例化,除了只是通过惯例使用您的API。我仍然将方法放在模块中,并将该模块视为单例。

If you do wish to use a class, there is no way of creating private classes or private constructors in Python, so you can't protect against multiple instantiations, other than just via convention in use of your API. I would still just put methods in a module, and consider the module as the singleton.

这篇关于有没有简单,优雅的方式来定义单身人士?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-25 21:28