'2022/07'에 해당되는 글 1건

  1. 2022.07.12 [Design Pattern] Singleton pattern
Coding/Python 삽질기2022. 7. 12. 21:26

파이썬 싱글톤 패턴

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

 

Design Patterns: Singleton in Python

Usage examples: A lot of developers consider the Singleton pattern an antipattern. That’s why its usage is on the decline in Python code. Identification: Singleton can be recognized by a static creation method, which returns the same cached object. Naïv

refactoring.guru

https://dojang.io/mod/page/view.php?id=2468 

 

파이썬 코딩 도장: 47.9 메타클래스 사용하기

메타클래스(metaclass)는 클래스를 만드는 클래스인데, 이 메타클래스를 구현하는 방법은 두 가지가 있습니다. type을 사용하여 동적으로 클래스를 생성하는 방식 type을 상속받아서 메타클래스를

dojang.io

 

'Coding > Python 삽질기' 카테고리의 다른 글

[Python] Python 소소한 기능들  (0) 2023.02.04
About Pyscript  (0) 2022.06.10
[Python] C 함수 호출 하기  (0) 2022.04.23
Posted by chobocho