Techioz Blog

Pythonでシングルトンメソッドを定義する方法

概要

Ruby には、インスタンスのシングルトン クラスにアクセスして変更できる方法が複数あります。 https://translate.google.com/translate?hl=ja&sl=en&tl=ja&u=https://ruby-doc.org/core-2.4.1/Object.html#method-i-singleton_class または https://translate.google.com/translate?hl=ja&sl=en&tl=ja&u=https://ruby-doc.org/core-2.4.1/Object.html#method-i-define_singleton_method

Python にも同様のものはありますか? または、ここで同じ結果を得る最も便利な方法は何ですか?

Python でシングルトン パターンを実装する方法をいくつか見つけました。しかし、もっと簡潔な方法があるかどうか興味があります

解決策

Python には、Ruby の define_singleton_method メソッドや singleton_class メソッドに直接相当するメソッドはありません。

クラスのインスタンスが 1 つだけ存在するシングルトン パターンを実装する場合は、メタクラスを使用できます。メタクラスを使用すると、クラスの作成をカスタマイズできます。

class SingletonMeta(type):
    _instances = {}

    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super(SingletonMeta, cls).__call__(*args, **kwargs)
        return cls._instances[cls]

class SingletonClass(metaclass=SingletonMeta):
    def some_method(self):
        print("Method of a singleton class")

instance1 = SingletonClass()
instance2 = SingletonClass()
print(instance1 is instance2)  # True - both are the same instance

しかし、これは私のやり方なので、もっと良い方法があるかもしれません。