首页 > 解决方案 > 列表继承方法的不可散列类型错误

问题描述

from collections import UserList

# same with X(list):
class  X(UserList):
    def method(self):
        print("It runs")

xx = X()
xx.method()
print(hash(xx.method))
# same with list's own methods:
# hash(xx.append)  # also causes TypeError

TypeError: unhashable type: 'X' Python < 3.8 的原因

关于如何使这项工作的任何想法?(除了升级解释器)

标签: python

解决方案


解决方法是在 init 中使用 lambda(有更好的选择吗?)。最初它必须从 pyee 库中将数据收集到类似列表的对象中。并使用列表继承对象的方法作为事件回调。

这是一个说明事情应该如何工作的示例:

from pyee import BaseEventEmitter
ee = BaseEventEmitter()

class Data(list):
    def __init__(self):
        super().__init__()
        self.store = lambda d: self.append(d)  # (!)workaround for py<3.8

storage = Data()
storage.store("some data") # test
print(hash(storage.store))  # This works in python 3.7

ee.on("received", storage.store)  # here we need it to be hashable
# ee.on("received", storage.append)  # and this fails in python 3.7
#... some even emitting code

推荐阅读