ホームページ  >  記事  >  バックエンド開発  >  Pythonでシングルトンパターンを実装する方法

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

爱喝马黛茶的安东尼
爱喝马黛茶的安东尼オリジナル
2019-06-22 09:28:412496ブラウズ

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 サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。