为什么我可以为一组添加正常的callables和方法,但不是<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>])
Run Code Online (Sandbox Code Playgroud)
编辑:我注意到这l.append.__hash__()也给出了这个错误
您无法将lists 添加到集合中,因为列表是可变的.只能将不可变对象添加到集合中.
l.append是一个实例方法.您可以将其视为元组(l, list.append)- 也就是说,它是与特定列表关联的list.append()方法l.list.append()方法是不可变的,但l不是.因此,虽然您可以添加list.append到该集合,但您无法添加l.append.
这有效:
>>> s.add(list.append)
Run Code Online (Sandbox Code Playgroud)
这不起作用:
>>> s.add((l, list.append))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
Run Code Online (Sandbox Code Playgroud)