lts*_*tar 11 python dictionary tuples list
我想使用类实例作为字典键,如:
classinstance = class()
dictionary[classinstance] = 'hello world'
Run Code Online (Sandbox Code Playgroud)
Python似乎无法将类作为字典键处理,或者我错了?另外,我可以使用像[(classinstance,helloworld),...]这样的元组列表而不是字典,但这看起来非常不专业.你有解决这个问题的线索吗?
But*_*840 12
您的实例需要可以清洗.该蟒蛇词汇表告诉我们:
一个目的是可哈希如果它有一个哈希值其寿命(它需要一个在这期间从不改变
__hash__()方法),并且可相对于其他对象(它需要一个__eq__()或__cmp__()方法).比较相等的可哈希对象必须具有相同的哈希值.Hashability使对象可用作字典键和set成员,因为这些数据结构在内部使用哈希值.
所有Python的不可变内置对象都是可清除的,而没有可变容器(例如列表或字典).默认情况下,作为用户定义类实例的对象是可清除的; 他们都比较不相等,他们的哈希值是他们的id().
以下代码运行良好,因为默认情况下,您的类对象是可清除的:
Class Foo(object):
def __init__(self):
pass
myinstance = Foo()
mydict = {myinstance : 'Hello world'}
print mydict[myinstance]
Run Code Online (Sandbox Code Playgroud)
输出:Hello world
此外,为了更高级的用法,你应该阅读这篇文章:
尝试在您的类中实现hash和eq方法.
例如,这是我制作的一个简单的哈希字典类:
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__()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10618 次 |
| 最近记录: |