我想在我的Python程序中实现某种单例模式.我想在不使用课程的情况下这样做; 也就是说,我想将所有与单例相关的函数和变量放在一个模块中,并将其视为一个实际的单例.
例如,假设这是在'singleton_module.py'文件中:
# singleton_module.py
# Singleton-related variables
foo = 'blah'
bar = 'stuff'
# Functions that process the above variables
def work(some_parameter):
global foo, bar
if some_parameter:
bar = ...
else:
foo = ...
Run Code Online (Sandbox Code Playgroud)
然后,程序的其余部分(即其他模块)将使用此单例,如下所示:
# another_module.py
import singleton_module
# process the singleton variables,
# which changes them across the entire program
singleton_module.work(...)
# freely access the singleton variables
# (at least for reading)
print singleton_module.foo
Run Code Online (Sandbox Code Playgroud)
这对我来说似乎是个好主意,因为它在使用单例的模块中看起来很干净.
然而,单身模块中所有这些繁琐的"全局"陈述都是丑陋的.它们出现在处理单例相关变量的每个函数中.在这个特定的例子中,这并不多,但是当你有10个以上的变量来管理多个函数时,它并不漂亮.
此外,如果您忘记了全局语句,这很容易出错:将创建函数本地的变量,并且不会更改模块的变量,这不是您想要的!
那么,这会被认为是干净的吗?是否有类似于我的方法可以消除"全球"混乱?
或者这根本不是要走的路?