似乎有很多方法可以在 Python 中定义 单例。关于 Stack Overflow 是否有共识?
原文由 Jamie 发布,翻译遵循 CC BY-SA 4.0 许可协议
似乎有很多方法可以在 Python 中定义 单例。关于 Stack Overflow 是否有共识?
原文由 Jamie 发布,翻译遵循 CC BY-SA 4.0 许可协议
这是我自己的单例实现。您所要做的就是装饰班级;要获得单身人士,您必须使用 Instance
方法。这是一个例子:
@Singleton
class Foo:
def __init__(self):
print 'Foo created'
f = Foo() # Error, this isn't how you get the instance of a singleton
f = Foo.instance() # Good. Being explicit is in line with the Python Zen
g = Foo.instance() # Returns already created instance
print f is g # True
这是代码:
class Singleton:
"""
A non-thread-safe helper class to ease implementing singletons.
This should be used as a decorator -- not a metaclass -- to the
class that should be a singleton.
The decorated class can define one `__init__` function that
takes only the `self` argument. Also, the decorated class cannot be
inherited from. Other than that, there are no restrictions that apply
to the decorated class.
To get the singleton instance, use the `instance` method. Trying
to use `__call__` will result in a `TypeError` being raised.
"""
def __init__(self, decorated):
self._decorated = decorated
def instance(self):
"""
Returns the singleton instance. Upon its first call, it creates a
new instance of the decorated class and calls its `__init__` method.
On all subsequent calls, the already created instance is returned.
"""
try:
return self._instance
except AttributeError:
self._instance = self._decorated()
return self._instance
def __call__(self):
raise TypeError('Singletons must be accessed through `instance()`.')
def __instancecheck__(self, inst):
return isinstance(inst, self._decorated)
原文由 Paul Manta 发布,翻译遵循 CC BY-SA 3.0 许可协议
2 回答5k 阅读✓ 已解决
2 回答1k 阅读✓ 已解决
4 回答893 阅读✓ 已解决
3 回答1.1k 阅读✓ 已解决
3 回答1.1k 阅读✓ 已解决
1 回答1.6k 阅读✓ 已解决
1 回答1.2k 阅读✓ 已解决
我真的不认为有必要,因为具有功能的模块(而不是类)可以很好地用作单例。它的所有变量都将绑定到模块,无论如何都不能重复实例化。
如果您确实希望使用一个类,则无法在 Python 中创建私有类或私有构造函数,因此除了通过使用 API 的约定之外,您无法防止多次实例化。我仍然只是将方法放在一个模块中,并将该模块视为单例。