class Point(object):
__cache = {}
def __new__(cls, x, y):
if (x, y) in Point.__cache:
return Point.__cache[(x, y)]
else:
o = object.__new__(cls)
o.x = x
o.y = y
Point.__cache[(x, y)] = o
return o
>>> Point(1, 2)
<__main__.Point object at 0xb6f5d24c>
>>> id(Point(1, 2)) == id(Point(1,2))
True
, 항상 IMO 간단하지만 필요한 경우 쉽게 클래스로 표현할 수 있기 때문에이 namedtuple
함께 기능을 사용 collections.namedtuple
from collections import namedtuple
def Point(x, y, _Point=namedtuple('Point', 'x y'), _cache={}):
return _cache.setdefault((x, y), _Point(x, y))
>>> Point(1, 2)
Point(x=1, y=2)
>>> id(Point(1, 2)) == id(Point(1, 2))
True
고려 :
class Point(namedtuple('Point', 'x y')):
__cache = {}
def __new__(cls, x, y):
return Point.__cache.setdefault((x, y),
super(cls, Point).__new__(cls, x, y))
@PetrViktorin 그의 answer에서 언급 한 바와 같이 당신은의 사용을 고려해야한다그래서 삭제 된 클래스 인스턴스 (분명히 namedtuple
과 작동하지 않음)는 사전 자체에서 참조 된 채 남아 있으므로 메모리에 남아 있지 않습니다.
이렇게하는 유일한 방법은 두 개체가 같은 개체가되도록 만드는 것입니다. 왜 이걸하고 싶어? – BrenBarn
유일한 방법은 같은 개체에 대한 두 개의 참조를 갖는 것입니다. –