有没有一种简单、优雅的方式来定义单身人士? [英] Is there a simple, elegant way to define singletons?

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

问题描述

似乎有很多方法可以在 Python 中定义单例.是否有关于 StackOverflow 的共识意见?

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.

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

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