自定义类型的对象作为字典键 [英] Object of custom type as dictionary key

查看:88
本文介绍了自定义类型的对象作为字典键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用自定义类型的对象作为Python字典中的键(我不希望对象id作为键),我该怎么办?

  class MyThing:
def __init __(self,name,location,length):
self.name = name
self.location = location
self.length = length

I '要使用MyThing作为键,如果名称和位置相同,则认为相同。
从C#/ Java我习惯于重写并提供一个equals和hashcode方法,并且承诺不突变哈希码依赖的任何东西。



在Python中我该怎么做才能完成这个?我应该呢



(在一个简单的情况下,像这里,或许最好只是放置一个(名称,位置)元组作为关键 - 但是考虑我想要关键成为一个对象)

解决方案

您需要添加 2方法,注意 __哈希__ __ eq __

  class MyThing:
def __init __(self,name,location,length):
self.name = name
self.location = location
self.length = length

def __hash __(self):
return hash((self.name ,self.location))

def __eq __(self,other):
return(self.name,self.location)==(other.name,other.location)

def __ne __(self,other):
#不是绝对必要的,但是要避免同时使用x == y和x!= y
#True同时
return not(self == other)

Python dict documentation 定义了关键对象的这些要求,即它们必须是 hashable


What must I do to use my objects of a custom type as keys in a Python dictionary (where I don't want the "object id" to act as the key) , e.g.

class MyThing:
    def __init__(self,name,location,length):
            self.name = name
            self.location = location
            self.length = length

I'd want to use MyThing's as keys that are considered the same if name and location are the same. From C#/Java I'm used to having to override and provide an equals and hashcode method, and promise not to mutate anything the hashcode depends on.

What must I do in Python to accomplish this ? Should I even ?

(In a simple case, like here, perhaps it'd be better to just place a (name,location) tuple as key - but consider I'd want the key to be an object)

解决方案

You need to add 2 methods, note __hash__ and __eq__:

class MyThing:
    def __init__(self,name,location,length):
        self.name = name
        self.location = location
        self.length = length

    def __hash__(self):
        return hash((self.name, self.location))

    def __eq__(self, other):
        return (self.name, self.location) == (other.name, other.location)

    def __ne__(self, other):
        # Not strictly necessary, but to avoid having both x==y and x!=y
        # True at the same time
        return not(self == other)

The Python dict documentation defines these requirements on key objects, i.e. they must be hashable.

这篇关于自定义类型的对象作为字典键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆