Flyweight
Flyweight
1使OOP

Python__new__
Flyweight
functools.lru_cache

class CachedTuple(tuple):
_cache = {}
def __new__(cls, value):
if not isinstance(value, tuple):
raise TypeError("CachedTuple ")
try:
h = hash(value)
except TypeError:
raise TypeError("")
if h in cls._cache:
return cls._cache[h]
instance = super().__new__(cls, value)
cls._cache[h] = instance
return instance
# 使
a = CachedTuple(("Taro", 22))
b = CachedTuple(("Taro", 22))
c = CachedTuple(("Hanako", 20))
print(a is b) # : True
print(a is c) # : False
#
try:
d = CachedTuple(["Taro", 22]) #
except TypeError as e:
print(e) # :