■ WeakValueDictionary 클래스를 사용해 약한 참조 딕셔너리 사용하는 방법을 보여준다.
▶ om.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import weakref class ObjectManager: def __init__(self): self.weakValueDictionary = weakref.WeakValueDictionary() def AddObject(self, sourceObject): sourceObjectID = id(sourceObject) self.weakValueDictionary[sourceObjectID] = sourceObject return sourceObjectID def GetObject(self, objectID): try: return self.weakValueDictionary[objectID] except: return None |
▶ main.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import om class Apple: pass apple1 = Apple() apple1.Color = "빨강" objectManager = om.ObjectManager() redID = objectManager.AddObject(apple1) apple2 = objectManager.GetObject(redID) print(apple1 is apple2) # True print(apple2.Color) # 빨강 |