사용자 도구

사이트 도구


python:singleton

차이

문서의 선택한 두 판 사이의 차이를 보여줍니다.

차이 보기로 링크

양쪽 이전 판이전 판
다음 판
이전 판
python:singleton [2017/06/01 04:37] rex8312python:singleton [2024/03/23 02:42] (현재) – 바깥 편집 127.0.0.1
줄 2: 줄 2:
  
 <code python> <code python>
 +# class Singleton(type):
 +#     _instances = {}
 +#     def __call__(cls, *args, **kwargs):
 +#         if cls not in cls._instances:
 +#             cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
 +#         return cls._instances[cls]
 +              
 class Singleton(type): class Singleton(type):
-    _instances = {} +     _instances = {} 
-     +     def __call__(cls, *args, **kwargs): 
-    def __call__(cls, *args, **kwargs): +         cls._instances.setdefault(clssuper().__call__(*args, **kwargs)
-        if cls not in cls._instances+         return cls._instances[cls]
-            cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) +
-        return cls._instances[cls]+
  
              
줄 27: 줄 32:
     print(MyClass().x)     print(MyClass().x)
 </code> </code>
-   + 
-* http://stackoverflow.com/questions/6760685/creating-a-singleton-in-python+  * https://medium.com/techtofreedom/3-levels-of-understanding-the-singleton-pattern-in-python-4bf429a10438   
 +  * http://stackoverflow.com/questions/6760685/creating-a-singleton-in-python 
python/singleton.1496291852.txt.gz · 마지막으로 수정됨: (바깥 편집)