以下の内容はhttps://px-wing.hatenablog.com/entry/2020/11/08/063208より取得しました。


Pythonデザインパターン-シングルトン

Pythonデザインパターン-シングルトン

  • クラスのインスタンス化を1つのオブジェクトに制限します。これは一種の作成パターンであり、メソッドと指定されたオブジェクトを作成するためのクラスは1つだけです。 作成されたインスタンスへのグローバルアクセスポイントを提供します。

サンプルコード

class Singleton:
   __instance = None
   @staticmethod 
   def getInstance():
      if Singleton.__instance == None:
         Singleton()
      return Singleton.__instance
   def __init__(self):
      if Singleton.__instance != None:
         raise Exception("このクラスはシングルトンです"")
      else:
         Singleton.__instance = self

s = Singleton()
print(s)

s = Singleton.getInstance()
print(s)

s = Singleton.getInstance()
print(s)

実行結果

<__main__.Singleton object at 0x7f17e1740400>
<__main__.Singleton object at 0x7f17e1740400>
<__main__.Singleton object at 0x7f17e1740400>

補足情報

@staticmethod 形式

-関数 デコレータ 。静的メソッドは (C.f() のよう) クラスから呼び出したり、 (C().f() のように) インスタンスから呼び出したりできます。 docs.python.org




以上の内容はhttps://px-wing.hatenablog.com/entry/2020/11/08/063208より取得しました。
このページはhttp://font.textar.tv/のウェブフォントを使用してます

不具合報告/要望等はこちらへお願いします。
モバイルやる夫Viewer Ver0.14