파이썬 싱글톤 패턴
class SingletonMeta(type):
_instance = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instance:
cls._instance[cls] = super().__call__(*args, **kwargs)
print("make first object")
else:
print("return a exist object")
return cls._instance[cls]
class Singleton(metaclass=SingletonMeta):
def __init__(self):
print("\nSingleton Init!")
def test_singleton():
singletone1 = Singleton()
singletone2 = Singleton()
print(f'{id(singletone1)} == {id(singletone2)} -> {id(singletone1) == id(singletone2)}')
Singleton Init!
make first object
return a exist object
2608647861000 == 2608647861000 -> True
참고
https://refactoring.guru/design-patterns/singleton/python/example
https://dojang.io/mod/page/view.php?id=2468
'Coding > Python 삽질기' 카테고리의 다른 글
[Python] Python 소소한 기능들 (0) | 2023.02.04 |
---|---|
About Pyscript (0) | 2022.06.10 |
[Python] C 함수 호출 하기 (0) | 2022.04.23 |