<p>使用Python实现单例模式的一种方法还可以是:</p>
<p>如果类的实例已经存在,则让singleton<code>__init()__</code>方法引发异常。更准确地说,类有一个成员<code>_single</code>。如果此成员与<code>None</code>不同,则会引发异常。</p>
<pre><code>class Singleton:
__single = None
def __init__( self ):
if Singleton.__single:
raise Singleton.__single
Singleton.__single = self
</code></pre>
<p>可以说,处理带有异常的单例实例创建也不是很干净。我们可以使用方法<code>handle()</code>隐藏实现细节,如</p>
<pre><code>def Handle( x = Singleton ):
try:
single = x()
except Singleton, s:
single = s
return single
</code></pre>
<^ >此{{CD5>}方法与单模式的C++实现非常类似。我们可以在<code>Singleton</code>类中有<code>handle()</code></p>
<pre><code>Singleton& Singleton::Handle() {
if( !psingle ) {
psingle = new Singleton;
}
return *psingle;
}
</code></pre>
<p>返回新的<code>Singleton</code>实例或对类<code>Singleton</code>的现有唯一实例的引用。</p>
<p><em>处理整个层次结构</em></p>
<p>如果<code>Single1</code>和<code>Single2</code>类从<code>Singleton</code>派生,则存在通过其中一个派生类的<code>Singleton</code>的单个实例。这可以用这个来验证:</p>
<pre><code>>>> child = S2( 'singlething' )
>>> junior = Handle( S1)
>>> junior.name()
'singlething'
</code></pre>