シングルトンを定義するシンプルでエレガントな方法はありますか?[重複]
-
09-06-2019 - |
質問
この質問にはすでに答えがあります:
- Python でシングルトンを作成する 20 件の回答
定義方法はいろいろあるようですが、 シングルトン Pythonで。Stack Overflow について一致した意見はありますか?
解決
(クラスではなく) 関数を備えたモジュールがシングルトンとして適切に機能するため、その必要性はあまりわかりません。そのすべての変数はモジュールにバインドされますが、とにかく繰り返しインスタンス化することはできません。
クラスを使用したい場合、Python ではプライベート クラスやプライベート コンストラクターを作成する方法がないため、API を使用する際の規則以外に複数のインスタンス化から保護することはできません。私はやはりモジュールにメソッドを置くだけで、そのモジュールをシングルトンと見なします。
他のヒント
これが私自身のシングルトンの実装です。あなたがしなければならないのは、クラスを装飾することだけです。シングルトンを取得するには、 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)
オーバーライドできます __new__
このような方法:
class Singleton(object):
_instance = None
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super(Singleton, cls).__new__(
cls, *args, **kwargs)
return cls._instance
if __name__ == '__main__':
s1 = Singleton()
s2 = Singleton()
if (id(s1) == id(s2)):
print "Same"
else:
print "Different"
Python でシングルトンを実装するための少し異なるアプローチは、 ボーグパターン Alex Martelli (Google 社員で Python の天才) 著。
class Borg:
__shared_state = {}
def __init__(self):
self.__dict__ = self.__shared_state
したがって、すべてのインスタンスに同じ ID を強制するのではなく、状態を共有します。
モジュールアプローチはうまく機能します。どうしてもシングルトンが必要な場合は、メタクラスのアプローチを好みます。
class Singleton(type):
def __init__(cls, name, bases, dict):
super(Singleton, cls).__init__(name, bases, dict)
cls.instance = None
def __call__(cls,*args,**kw):
if cls.instance is None:
cls.instance = super(Singleton, cls).__call__(*args, **kw)
return cls.instance
class MyClass(object):
__metaclass__ = Singleton
この実装は次から参照してください PEP318, 、デコレーターを使用してシングルトン パターンを実装します。
def singleton(cls):
instances = {}
def getinstance():
if cls not in instances:
instances[cls] = cls()
return instances[cls]
return getinstance
@singleton
class MyClass:
...
として 受け入れられた回答 最も慣用的な方法は次のとおりです モジュールを使用する.
それを念頭に置いて、概念実証を次に示します。
def singleton(cls):
obj = cls()
# Always return the same object
cls.__new__ = staticmethod(lambda cls: obj)
# Disable __init__
try:
del cls.__init__
except AttributeError:
pass
return cls
を参照してください。 Python データモデル 詳細については __new__
.
例:
@singleton
class Duck(object):
pass
if Duck() is Duck():
print "It works!"
else:
print "It doesn't work!"
ノート:
新しいスタイルのクラス (から派生) を使用する必要があります。
object
) このために。シングルトンは、初めて使用されるときではなく、定義されたときに初期化されます。
これは単なるおもちゃの例です。実際にこれを製品コードで使用したことはありませんし、使用する予定もありません。
これについてはよくわかりませんが、私のプロジェクトでは「規約シングルトン」(強制シングルトンではありません)を使用しています。つまり、次のクラスがあるとします。 DataController
, 、同じモジュールでこれを定義します。
_data_controller = None
def GetDataController():
global _data_controller
if _data_controller is None:
_data_controller = DataController()
return _data_controller
全部で6行なのでエレガントではありません。しかし、私のシングルトンはすべてこのパターンを使用しており、少なくとも非常に明示的です (Python 的です)。
の Python ドキュメント これをカバーします:
class Singleton(object):
def __new__(cls, *args, **kwds):
it = cls.__dict__.get("__it__")
if it is not None:
return it
cls.__it__ = it = object.__new__(cls)
it.init(*args, **kwds)
return it
def init(self, *args, **kwds):
pass
おそらく次のように書き直すと思います。
class Singleton(object):
"""Use to create a singleton"""
def __new__(cls, *args, **kwds):
"""
>>> s = Singleton()
>>> p = Singleton()
>>> id(s) == id(p)
True
"""
self = "__self__"
if not hasattr(cls, self):
instance = object.__new__(cls)
instance.init(*args, **kwds)
setattr(cls, self, instance)
return getattr(cls, self)
def init(self, *args, **kwds):
pass
これを拡張すると比較的きれいになるはずです。
class Bus(Singleton):
def init(self, label=None, *args, **kwds):
self.label = label
self.channels = [Channel("system"), Channel("app")]
...
一度、Python でシングルトンを作成したとき、すべてのメンバー関数にクラスメソッド デコレータがあるクラスを使用しました。
class foo:
x = 1
@classmethod
def increment(cls, y = 1):
cls.x += y
Google Testing ブログには、シングルトンがなぜ悪いのか、またはその可能性があり、アンチパターンであるのかを論じた興味深い記事もいくつかあります。
今後クラスを装飾 (アノテーション) したい場合は、シングルトン デコレータ (別名アノテーション) を作成するのがエレガントな方法です。次に、クラス定義の前に @singleton を置くだけです。
def singleton(cls):
instances = {}
def getinstance():
if cls not in instances:
instances[cls] = cls()
return instances[cls]
return getinstance
@singleton
class MyClass:
...
以下は Peter Norvig の Python IAQ の例です。 Python でシングルトン パターンを実行するにはどうすればよいですか? (この質問を見つけるにはブラウザの検索機能を使用する必要があります。申し訳ありませんが、直接リンクはありません)
また、ブルース・エッケルの著書には別の例があります。 Pythonで考える (ここでもコードへの直接リンクはありません)
私はそう思います 強制する クラスまたはインスタンスをシングルトンにするのはやりすぎです。個人的には、通常のインスタンス化可能なクラス、半プライベート参照、および単純なファクトリー関数を定義するのが好きです。
class NothingSpecial:
pass
_the_one_and_only = None
def TheOneAndOnly():
global _the_one_and_only
if not _the_one_and_only:
_the_one_and_only = NothingSpecial()
return _the_one_and_only
または、モジュールが最初にインポートされたときにインスタンス化に問題がない場合は、次のようにします。
class NothingSpecial:
pass
THE_ONE_AND_ONLY = NothingSpecial()
そうすれば、副作用なしで新しいインスタンスに対するテストを作成でき、モジュールにグローバル ステートメントを散りばめる必要がなく、必要に応じて将来バリアントを派生できます。
Python で実装されたシングルトン パターン ActiveState のご厚意による。
トリックは、インスタンスを 1 つだけ持つことになっているクラスを別のクラスの中に置くことのようです。
Python については比較的初心者なので、最も一般的な表現が何かはわかりませんが、私が思いつく最も単純なことは、クラスの代わりにモジュールを使用することです。クラスのインスタンス メソッドだったものは、モジュールでは単なる関数になり、すべてのデータはクラスのメンバーではなくモジュールの変数になります。これは、人々がシングルトンを使用するタイプの問題を解決するための Python 的なアプローチではないかと思います。
本当にシングルトン クラスが必要な場合は、適切な実装が説明されています。 Googleで最初にヒットした 「Python シングルトン」の場合、具体的には次のようになります。
class Singleton:
__single = None
def __init__( self ):
if Singleton.__single:
raise Singleton.__single
Singleton.__single = self
それでうまくいくようです。
OK、シングルトンは良いことも悪いこともある、私は知っています。これは私の実装であり、内部にキャッシュを導入し、異なる型の多数のインスタンス、または異なる引数を持つ同じ型の多数のインスタンスを生成するという古典的なアプローチを拡張しただけです。
これを Singleton_group と呼びました。これは、類似したインスタンスをグループ化し、同じ引数を持つ同じクラスのオブジェクトが作成されるのを防ぐためです。
# Peppelinux's cached singleton
class Singleton_group(object):
__instances_args_dict = {}
def __new__(cls, *args, **kwargs):
if not cls.__instances_args_dict.get((cls.__name__, args, str(kwargs))):
cls.__instances_args_dict[(cls.__name__, args, str(kwargs))] = super(Singleton_group, cls).__new__(cls, *args, **kwargs)
return cls.__instances_args_dict.get((cls.__name__, args, str(kwargs)))
# It's a dummy real world use example:
class test(Singleton_group):
def __init__(self, salute):
self.salute = salute
a = test('bye')
b = test('hi')
c = test('bye')
d = test('hi')
e = test('goodbye')
f = test('goodbye')
id(a)
3070148780L
id(b)
3070148908L
id(c)
3070148780L
b == d
True
b._Singleton_group__instances_args_dict
{('test', ('bye',), '{}'): <__main__.test object at 0xb6fec0ac>,
('test', ('goodbye',), '{}'): <__main__.test object at 0xb6fec32c>,
('test', ('hi',), '{}'): <__main__.test object at 0xb6fec12c>}
すべてのオブジェクトはシングルトン キャッシュを保持します...これは悪いことかもしれませんが、一部の人にとってはうまくいきます:)
class Singleton(object[,...]):
staticVar1 = None
staticVar2 = None
def __init__(self):
if self.__class__.staticVar1==None :
# create class instance variable for instantiation of class
# assign class instance variable values to class static variables
else:
# assign class static variable values to class instance variables
関数パラメータのデフォルト値に基づく私の簡単な解決策。
def getSystemContext(contextObjList=[]):
if len( contextObjList ) == 0:
contextObjList.append( Context() )
pass
return contextObjList[0]
class Context(object):
# Anything you want here
シングルトンの異母兄弟
私は staale に完全に同意し、シングルトンのハーフブラザーを作成するサンプルをここに残しておきます。
class void:pass
a = void();
a.__class__ = Singleton
a
シングルトンのように見えなくても、シングルトンと同じクラスであると報告されるようになります。したがって、複雑なクラスを使用するシングルトンは、あまりいじらないことに依存することになります。
そのため、変数やモジュールなどのより単純なものを使用して、同じ効果を得ることができます。それでも、わかりやすくするためにクラスを使用したい場合は、 Pythonではクラスはオブジェクトです, 、つまり、オブジェクトはすでにあります(インスタンスではありませんが、同じように機能します)。
class Singleton:
def __new__(cls): raise AssertionError # Singletons can't have instances
そこでは、インスタンスを作成しようとすると素晴らしいアサーション エラーが発生しますが、導出に静的メンバーを保存し、実行時にそれらに変更を加えることができます (私は Python が大好きです)。このオブジェクトは他の約半兄弟と同じくらい優れています (必要に応じて作成することもできます) が、単純さのため実行速度が速くなる傾向があります。
class Singeltone(type):
instances = dict()
def __call__(cls, *args, **kwargs):
if cls.__name__ not in Singeltone.instances:
Singeltone.instances[cls.__name__] = type.__call__(cls, *args, **kwargs)
return Singeltone.instances[cls.__name__]
class Test(object):
__metaclass__ = Singeltone
inst0 = Test()
inst1 = Test()
print(id(inst1) == id(inst0))
上記のメタクラスベースのソリューションが望ましくなく、単純な関数デコレータベースのアプローチが気に入らない場合 (例:その場合、シングルトン クラスの静的メソッドは機能しないため)、この妥協策は機能します。
class singleton(object):
"""Singleton decorator."""
def __init__(self, cls):
self.__dict__['cls'] = cls
instances = {}
def __call__(self):
if self.cls not in self.instances:
self.instances[self.cls] = self.cls()
return self.instances[self.cls]
def __getattr__(self, attr):
return getattr(self.__dict__['cls'], attr)
def __setattr__(self, attr, value):
return setattr(self.__dict__['cls'], attr, value)