在Python中,我可以使用对象(类的实例)作为字典键吗?

2024-05-16 12:53:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我想使用类实例作为字典键,例如:

classinstance = class()
dictionary[classinstance] = 'hello world'

Python似乎无法将类作为字典键处理,或者我错了? 此外,我可以使用类似于[(classinstance,helloworld),…]的元组列表来代替字典,但这看起来非常不专业。 你有解决那个问题的线索吗?


Tags: 实例hello列表worlddictionary字典专业class
3条回答

以下代码运行良好,因为默认情况下,类对象是散列的:

Class Foo(object):
    def __init__(self):
        pass

myinstance = Foo()
mydict = {myinstance : 'Hello world'}

print mydict[myinstance]

输出: 你好,世界

此外,对于更高级的用法,您应该阅读以下文章:

Object of custom type as dictionary key

你的实例需要是散列的。python glossary告诉我们:

An object is hashable if it has a hash value which never changes during its lifetime (it needs a __hash__() method), and can be compared to other objects (it needs an __eq__() or __cmp__() method). Hashable objects which compare equal must have the same hash value.

Hashability makes an object usable as a dictionary key and a set member, because these data structures use the hash value internally.

All of Python’s immutable built-in objects are hashable, while no mutable containers (such as lists or dictionaries) are. Objects which are instances of user-defined classes are hashable by default; they all compare unequal, and their hash value is their id().

尝试在类中实现hasheq方法。

例如,下面是我创建的一个简单的哈希字典类:

class hashable_dict:
    def __init__(self, d):
        self.my_dict = d
        self.my_frozenset = frozenset(d.items())
    def __getitem__(self, item):
        return self.my_dict[item]
    def __hash__(self):
        return hash(self.my_frozenset)
    def __eq__(self, rhs):
        return isinstance(rhs, hashable_dict) and self.my_frozenset == rhs.my_frozenset
    def __ne__(self, rhs):
       return not self == rhs
    def __str__(self):
        return 'hashable_dict(' + str(self.my_dict) + ')'
    def __repr__(self):
        return self.__str__()

相关问题 更多 >