私たちは皆あなたの質問を無視しており、代わりに代替のシングルトン実装を提案しているので、私のお気に入りに参加します. これは、Python モジュールを何回インポートしても、一度しかロードされないという事実を利用しています。
また、Python のモットーである "私たちは皆、大人の同意を得ています" にも基づいています。なぜなら、本当にしたいのであれば、複数回インスタンス化することができます...しかし、それを間違って行うには、本当に余分な努力をしなければならないからです。
だからでmysingleton.py
:
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
次に、次のように使用します。
from mysingleton import Singleton
# Use it!
間違ったことをするために余計な努力をしなければならないと言いました。シングルトン クラスの 2 つのインスタンスを作成して、シングルトンではなくする方法を次に示します。
another_instance = Singleton.__class__()
では、この問題を回避するにはどうすればよいでしょうか。私は医者を引用します:それをしないでください!
注:これは、以下のコメントが作成された後に追加されました
私がそれに取り組んでいる間、複雑なコードの量を最小限に抑える別のシングルトンバリアントを次に示します。メタクラスを使用します:
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
Python 3 では、代わりに次のようにシングルトン インスタンスを作成します。
class Singleton(metaclass=SingletonMeta):
attribute = "One... two... five!"
singleton はclassであり、singletonのインスタンスを作成できるため、これはもう少し不安定です。シングルトンはインスタンスがあってもシングルトンのままであるため、理論的にはこれで問題ありませんが、シングルトンではないことを覚えておく必要があります。シングルトン属性をそのインスタンスでクラス属性としてすぐに使用できるようにする必要がある場合もあります。Singleton()
Singleton