为什么我可以将普通的可调用对象和方法添加到集合中,但不能 <some list>.append
(例如)?
例如:
>>> l = []
>>> s = set()
>>> s.add(l.append)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>> type(l.append)
<type 'builtin_function_or_method'>
>>> type(map)
<type 'builtin_function_or_method'>
>>> s.add(map)
>>> def func(): print 'func'
...
>>> s.add(func)
>>> print s
set([<built-in function map>, <function func at 0x10a659758>])
编辑:我注意到 l.append.__hash__()
也给出这个错误
最佳答案
您不能将 list
添加到集合中,因为列表是可变的。只能将不可变对象(immutable对象)添加到集合中。
l.append
是一个实例方法。您可以将其视为元组 (l, list.append)
— 也就是说,它是绑定(bind)到特定列表 l
的 list.append() 方法. list.append() 方法是不可变的,但 l
不是。因此,虽然您可以将 list.append
添加到集合中,但您不能添加 l.append
。
这个有效:
>>> s.add(list.append)
这不起作用:
>>> s.add((l, list.append))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
关于python - 为什么我不能将 <some list>.append 添加到 python 集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13596430/