0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[Python] Singletonの実装

Posted at

概要

今更どこに需要があるのかわかりませんが,Pythonにおけるシングルトンパターン(Singleton Pattern)の実現パターン(を自分用にChatGPTに訊いたもの)をメモしておきます.

方法1: クラス変数を使った実装

class Singleton:
    _instance = None

    def __new__(cls, *args, **kwargs):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
            
        return cls._instance

方法2: デコレータを使った実装

def singleton(cls):
    instances = {}
    def get_instance(*args, **kwargs):
        if cls not in instances:
            instances[cls] = cls(*args, **kwargs)
        return instances[cls]
    return get_instance

@singleton
class MyClass:
    pass

方法3: モジュールを使った実装(Pythonic)

# singleton_module.py
class Config:
    def __init__(self):
        self.value = 42

config = Config()

# 別ファイルや他の場所から
# from singleton_module import config

NOTE

  • モジュール自体が一度しか読み込まれないため,モジュールレベルでインスタンスを作れば自然にシングルトンになります.
0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?