如何通过自定义对象值在Python中访问字典值?

7 投票
4 回答
3845 浏览
提问于 2025-04-15 21:24

我有一个正方形,这个正方形是由一系列点组成的。在每个点上都有一个对应的值。

我想做的是建立一个像这样的字典:

class Point:
    def __init__(self, x, y):
        self._x = x
        self._y = y


square = {}    
for x in range(0, 5):
        for y in range(0, 5):
            point = Point(x,y)
            square[point] = None

但是,如果我后来创建一个新的点对象,想用这个点作为键去查字典里的值,却发现不行……

>> square[Point(2,2)]
Traceback (most recent call last):
  File "<pyshell#19>", line 1, in <module>
    square[Point(2,2)]
KeyError: <__main__.Point instance at 0x02E6C378>

我猜这可能是因为Python认为两个属性相同的对象并不是同一个对象?有没有什么办法可以解决这个问题?谢谢!

4 个回答

2

有没有什么理由不直接使用元组呢:

>>> s={}
>>> s[1,2]=5
>>> s
{(1, 2): 5}
>>> s[1,2]
5
5

是的,在你的 Point 类里面定义 __eq____hash__ 这两个方法。

class Point:
    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

    def __hash__(self):
        #This one's up to you, but it should be unique. Something like x*1000000 + y.
12

定义 Point.__hash__()Point.__eq__() 这样可以让它们在字典中正确比较。

顺便提一下,考虑定义 Point.__repr__(),这样你可以得到看起来不错的 Point 对象表示。

撰写回答