from weakref import WeakValueDictionary
class _Point(object):
def __init__(self, x, y):
self.x = x
self.y = y
# Cache of Point objects the program currently uses
_points = WeakValueDictionary()
def Point(x, y):
"""Create a Point object"""
# Note that this is a function (a "factory function")
# You can also override Point.__new__ instead
try:
return _points[x, y]
except KeyError:
_points[x, y] = point = _Point(x, y)
return point
if __name__ == '__main__':
# A basic demo
print Point(1, 2)
print id(Point(1, 2))
print Point(2, 3) == Point(2, 3)
pt_2_3 = Point(2, 3)
# The Point(1, 2) we created earlier is not needed any more.
# In current CPython, it will have been been garbage collected by now
# (but note that Python makes no guarantees about when objects are deleted)
# If we create a new Point(1, 2), it should get a different id
print id(Point(1, 2))
>>> class Point(object):
... def __init__(self, x, y):
... self.x = x
... self.y = y
... def __eq__(self, other):
... return self.x == other.x and self.y == other.y
...
>>> a = Point(1,2)
>>> b = Point(1,2)
>>> a == b
True
>>> b = Point(2,2)
>>> a == b
False
您需要有一个对象的全局字典,并通过工厂函数(或自定义的} ,这样就不会不必要地用不再需要的对象填满内存。在
__new__
)获取它们,请参阅其他答案)。另外,考虑使用^{请注意,namedtuple不能与WeakValueDictionary一起使用。在
如果需要比较两个对象是否包含相同的值,则可以实现eq operator:
当您需要一个真正简单的类,如
^{pr2}$Point
,请始终考虑collections.namedtuple
我在
namedtuple
旁边使用了一个函数,因为它在IMO中更简单,但如果需要,可以很容易地将其表示为类:正如@PetrViktorin在他的answer中指出的那样,您应该考虑使用^{} ,因此删除的类实例(显然与
namedtuple
无关)不会保留在内存中,因为它们仍然在字典中被引用。在相关问题 更多 >
编程相关推荐