<p>既然我们都忽略了你的问题,而是提出了其他的单例实现方案,我将介绍我最喜欢的。它利用了python模块只加载一次的事实,不管您导入它多少次。</p>
<p>它也基于python的座右铭“<em>我们都同意这里的成年人</em>”,因为如果你真的想,你可以<em>多次实例化它。。。但是你真的要付出额外的努力去做错事。</p>
<p>所以在<code>mysingleton.py</code>中:</p>
<pre><code>class SingletonClass(object):
def __init__(self):
# There's absolutely nothing special about this class
# Nothing to see here, move along
pass
# Defying PEP8 by capitalizing name
# This is to point out that this instance is a Singleton
Singleton = SingletonClass()
# Make it a little bit harder to use this module the wrong way
del SingletonClass
</code></pre>
<p>然后像这样使用:</p>
<pre><code>from mysingleton import Singleton
# Use it!
</code></pre>
<p>我说你必须付出额外的努力去做错事。下面是如何创建singleton类的两个实例,使其不再是singleton类:</p>
<pre><code>another_instance = Singleton.__class__()
</code></pre>
<p>那么你如何避免这个问题呢?我引用医生的话:<em>那就不要那样做!</em></p>
<hr/>
<p><strong>注意:这是在发表以下评论之后添加的</strong></p>
<p>当我在这里的时候,这里有另一个单例变量,它最小化了复杂代码的数量。它使用元类:</p>
<pre><code>class SingletonMeta(type):
# All singleton methods go in the metaclass
def a_method(cls):
return cls.attribute
# Special methods work too!
def __contains__(cls, item):
return item in cls.a_list
class Singleton(object):
__metaclass__ = SingletonMeta
attribute = "All attributes are class attributes"
# Just put initialization code directly into the class
a_list = []
for i in range(0, 100, 3):
a_list.append(i)
print Singleton.a_method()
print 3 in Singleton
</code></pre>
<p>在Python3中,您将创建如下的单例实例:</p>
<pre><code>class Singleton(metaclass=SingletonMeta):
attribute = "One... two... five!"
</code></pre>
<p>现在这个有点不确定了,因为singleton是一个<em>类</em>,您可以创建<em>singleton</em>的<em>实例</em>。理论上这是可以的,因为即使有实例,singleton仍然是singleton,但是您需要记住<code>Singleton()</code>不是singleton--<code>Singleton</code>!它甚至可以满足您的需要,将singleton属性作为类属性随时提供给它的实例。</p>