<aside> 💡 객체 지향 프로그래밍 디자인 패턴의 하나로, 특정 클래스의 인스턴스가 프로그램 전체에서 하나만 존재해야 할 때 사용합니다.
</aside>
싱글턴을 사용하지 않았을 때
class Theme:
def __init__(self, dark_mode=False):
self.dark_mode = dark_mode
class Tab:
def __init__(self, name):
self.name = name
self.theme = Theme() # 각 탭마다 새로운 Theme 인스턴스 생성
tab_1 = Tab("Home")
tab_2 = Tab("Profile")
tab_1_is_dark_a = tab_1.theme.dark_mode
tab_2_is_dark_a = tab_2.theme.dark_mode
tab_1.theme.dark_mode = True
tab_1_is_dark_b = tab_1.theme.dark_mode
tab_2_is_dark_b = tab_2.theme.dark_mode
pass
싱글턴 사용
class Theme:
_instance = None
def __new__(cls, dark_mode=False):
if cls._instance is None:
cls._instance = super(Theme, cls).__new__(cls)
cls._instance.dark_mode = dark_mode
return cls._instance
class Tab:
def __init__(self, name):
self.name = name
self.theme = Theme() # 모든 탭에서 동일한 Theme 인스턴스 공유
tab_1 = Tab("Home")
tab_2 = Tab("Profile")
tab_1_is_dark_a = tab_1.theme.dark_mode
tab_2_is_dark_a = tab_2.theme.dark_mode
tab_1.theme.dark_mode = True
tab_1_is_dark_b = tab_1.theme.dark_mode
tab_2_is_dark_b = tab_2.theme.dark_mode
pass
__new__() 메소드 : 인스턴스 생성 과정을 커스터마이징할 때 사용| 구분 | __new__ |
__init__ |
|---|---|---|
| 역할 | 객체(인스턴스) 생성 | 객체(인스턴스) 초기화 |
| 타입 | 클래스 메소드 | 인스턴스 메소드 |
| 사용 시점 | 객체가 메모리에 생성될 때 호출 | **__new__**로 생성된 객체를 초기화할 때 호출 |
| 첫 번째 인자 | 클래스 자체 (cls) |
인스턴스 자체 (self) |
| 반환값 | 새로 생성된 인스턴스 | None (반환값이 있으면 안 됨) |
| 호출 방식 | **object**의 __new__를 명시적으로 호출 필요 (super().__new__(cls, ...)) |
객체 생성시 파이썬이 자동으로 호출 |
<aside> 🧠 파이썬의 __new__가 사용되는 흔한 용도 중 싱글턴 외의 예시를 들어줘.
</aside>