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

在Python中通过自定义对象值访问字典值?,python,dictionary,object,Python,Dictionary,Object,我有一个由一系列点组成的正方形。每个点都有一个对应的值 我想做的是建立一个这样的字典: 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[poi

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

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

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
但是,如果我稍后创建一个新的point对象,并尝试使用该点的键访问字典的值,则它将不起作用

>> 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>
>正方形[点(2,2)]
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
平方[点(2,2)]
关键错误:

我猜这是因为Python没有考虑两个具有相同属性的对象是同一个对象吗?这有什么办法吗?感谢您定义和,以便在dicts中正确比较它们


当你在这一点时,考虑一下定义,这样你就可以得到你的<代码>点对象的体面的表示。

< P>是的,在你的Point类中定义<代码>
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.

不使用元组的任何原因:

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

步骤:实现自定义密钥类并重写哈希和相等函数

e、 g

主要方法
有关完整的详细信息,请参阅本文。

谢谢!关于repr的好提示,但我对它和str之间的区别有点困惑?
\uuu repr\uuu()
在需要对象表示时使用,而实际上不需要字符串值,例如在REPL中。
\uu repr\uu
也应该返回有效的python,可以将其作为参数传递到
eval
,以创建与所报告对象相同的对象。它应该返回以下字符串:
'Point(%s,%s)%(self.\u x,self.\u y)
在该示例中,我想我可以,但在我的代码中,Point类还有一些属性,因此元组是不够的。请查看collections模块中的namedtuple函数。我发现它对于实现类似结构的对象非常有用,如果您想添加其他方法,它会创建可以从中继承的类。感谢代码分解,真的很有帮助!但愿我也能选择你作为答案。uuuu hash_uuuuu()方法可以实现为“return(x,y)。uuuu hash_uuuuu()。
class CustomDictKey(object):

def __init__(self, 
             param1,
             param2):

            self._param1 = param1
            self._param2 = param2

 # overriding hash and equality function does the trick

def __hash__(self):
    return hash((self._param1,
             self._param2))

def __eq__(self, other):
    return ( ( self._param1,
             self._param2 ) == ( other._param1,
             other._param2) )

def __str__(self):
    return "param 1: {0} param 2: {1}  ".format(self._param1, self._param2)
if name == 'main':

    # create custom key
    k1  = CustomDictKey(10,5)

    k2  = CustomDictKey (2, 4)

    dictionary = {}

    #insert elements in dictionary with custom key
    dictionary[k1] = 10
    dictionary[k2] = 20

    # access dictionary values with custom keys and print values
    print "key: ", k1, "val :", dictionary[k1]
    print "key: ", k2, "val :", dictionary[k2]