python - 列表继承方法的不可散列类型错误
问题描述
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 的原因
关于如何使这项工作的任何想法?(除了升级解释器)
解决方案
解决方法是在 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
推荐阅读
- python - 根据共享值组合 CSV 文件
- javascript - 为什么我的图像在双击它们时会移动位置?
- python - ValueError:没有足够的值来解包(预期 4,得到 3)
- javascript - HTML、CSS、JS:使用按钮和事件监听器猜测游戏网页:提示和重置按钮不起作用
- python - 在 Cython 中附加 C 数组(或任何数组)的最佳方法
- python - Groupby 按日期排序,根据其他列值找到最小值、最大值
- maven - 将 artifactId 传递给 surefire argLine
- r - 一次导入多个 .tsv 文件作为数据框
- scala - Scala:将用户输入读取为单个字符串
- python - 如何重定向以使用新上下文而不是 django 的原始上下文?