Pythonでシングルトンパターンを実装する方法

爱喝马黛茶的安东尼
リリース: 2019-06-22 09:28:41
オリジナル
2408 人が閲覧しました

Pythonでシングルトンパターンを実装する方法

Python でシングルトン モードを実装するにはどうすればよいですか?ここでは 7 つの異なるメソッドを紹介します:

##1: staticmethod

コードは次のとおりです:

class Singleton(object):
    instance = None
    def __init__(self):
        raise SyntaxError('can not instance, please use get_instance')
    def get_instance():
        if Singleton.instance is None:
            Singleton.instance = object.__new__(Singleton)
        return Singleton.instance
a = Singleton.get_instance()
b = Singleton.get_instance()
print('a id=', id(a))
print('b id=', id(b))
ログイン後にコピー

このメソッド重要な点は、__init__ で例外をスローし、クラスを介したインスタンス化を禁止し、静的 get_instance 関数を介してのみインスタンスを取得することです。クラスを介してインスタンス化できないため、静的 get_instance 関数は親クラス オブジェクトを介して取得できます。__new__ インスタンス化します。

2: classmethod

メソッド 1 と同様、コード:

class Singleton(object):
    instance = None
    def __init__(self):
        raise SyntaxError('can not instance, please use get_instance')
    def get_instance(cls):
        if Singleton.instance is None:
            Singleton.instance = object.__new__(Singleton)
        return Singleton.instance
a = Singleton.get_instance()
b = Singleton.get_instance()
print('a id=', id(a))
print('b id=', id(b))
ログイン後にコピー

このメソッドの主なポイントは、__init__ で例外をスローし、次のことを禁止することです。渡し クラスをインスタンス化するには、静的な get_instance 関数を通じてのみインスタンスを取得できます。インスタンスはクラスを通じてインスタンス化できないため、静的な get_instance 関数は親クラス object.__new__ を通じてインスタンス化できます。

3: クラス属性メソッド

# はメソッド 1、コード:

class Singleton(object):
    instance = None
    def __init__(self):
        raise SyntaxError('can not instance, please use get_instance')
    def get_instance():
        if Singleton.instance is None:
            Singleton.instance = object.__new__(Singleton)
        return Singleton.instance
a = Singleton.get_instance()
b = Singleton.get_instance()
print(id(a))
print(id(b))
ログイン後にコピー

と似ています。このメソッドの主なポイントは、例外をスローすることです。 __init__、クラスを通じてインスタンス化することは禁止されており、インスタンスは静的な get_instance 関数を通じてのみ取得できます。クラスを通じてインスタンス化できないため、静的な get_instance 関数は親クラス オブジェクトを通じてインスタンス化できます。__new__。

4: __new__

一般的なメソッドのコードは次のとおりです:

class Singleton(object):
    instance = None
    def __new__(cls, *args, **kw):
        if not cls.instance:
            # cls.instance = object.__new__(cls, *args)
            cls.instance = super(Singleton, cls).__new__(cls, *args, **kw)
        return cls.instance
a = Singleton()
b = Singleton()
print(id(a))
print(id(b))
ログイン後にコピー

関連する推奨事項: 「

Python ビデオ チュートリアル 」 "

#5: デコレーター

コードは次のとおりです:

def Singleton(cls):
    instances = {}
    def getinstance():
        if cls not in instances:
            instances[cls] = cls()
        return instances[cls]
    return getinstance
class MyClass:
    pass
a = MyClass()
b = MyClass()
c = MyClass()
print(id(a))
print(id(b))
print(id(c))
ログイン後にコピー

6: メタクラス

python2 バージョン:

class Singleton(type):
    def __init__(cls, name, bases, dct):
        super(Singleton, cls).__init__(name, bases, dct)
        cls.instance = None
    def __call__(cls, *args):
        if cls.instance is None:
            cls.instance = super(Singleton, cls).__call__(*args)
        return cls.instance
class MyClass(object):
    __metaclass__ = Singleton
a = MyClass()
b = MyClass()
c = MyClass()
print(id(a))
print(id(b))
print(id(c))
print(a is b)
print(a is c)
ログイン後にコピー

または:

class Singleton(type):
    def __new__(cls, name, bases, attrs):
        attrs["_instance"] = None
        return super(Singleton, cls).__new__(cls, name, bases, attrs)
    def __call__(cls, *args, **kwargs):
        if cls._instance is None:
            cls._instance = super(Singleton, cls).__call__(*args, **kwargs)
        return cls._instance
class Foo(object):
    __metaclass__ = Singleton
x = Foo()
y = Foo()
print(id(x))
print(id(y))
ログイン後にコピー

python3 バージョン:


class Singleton(type):
    def __new__(cls, name, bases, attrs):
        attrs['instance'] = None
        return super(Singleton, cls).__new__(cls, name, bases, attrs)
    def __call__(cls, *args, **kwargs):
        if cls.instance is None:
            cls.instance = super(Singleton, cls).__call__(*args, **kwargs)
        return cls.instance
class Foo(metaclass=Singleton):
    pass
x = Foo()
y = Foo()
print(id(x))
print(id(y))
ログイン後にコピー

7: 名前カバレッジ

# #コードは次のとおりです:

class Singleton(object):
    def foo(self):
        print('foo')
    def __call__(self):
        return self
Singleton = Singleton()
Singleton.foo()
a = Singleton()
b = Singleton()
print(id(a))
print(id(b))
ログイン後にコピー

以上がPythonでシングルトンパターンを実装する方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ソース:php.cn
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
最新の問題
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!