Skip to main content
 首页 » 编程设计

python之为对象实例提供全局访问点

2025年05月04日18pander-it

想象一个系统 (Python),其中的不同部分不断地与给定对象的一个​​实例交互。为该实例提供全局访问点的最佳方式是什么?

到目前为止,我只能考虑在 __init__.py 中构建(Singleton)实例并根据需要导入模块:

# __init__.py 
class Thing(object, Singleton): 
 pass 
 
TheThing = Thing() 
 
__all__ = ['TheThing']   

是否有更好的方法为 TheThing 提供全局访问点?

谢谢,

J.

请您参考如下方法:

不要在 python 中使用 singletons。 Python 模块是很棒的单例(它们只初始化一次,随处可用),如果需要,您可以将全局变量合二为一。

这是解释:Is there a simple, elegant way to define singletons?