在索引字典时,Python NoneType不可调用

4 投票
2 回答
1354 浏览
提问于 2025-04-17 12:01

我遇到了一个奇怪的错误,搞不懂是什么原因。

Python 2.7.1+ (r271:86832, Apr 11 2011, 18:05:24) 
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import UserDict
>>> a = UserDict.UserDict()
>>> b = {}
>>> b[a]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not callable

我知道这应该是个错误。但我不明白为什么会出现 'NoneType' object is not callable 这个提示。根据我的理解,在导致错误的那一行,我并没有调用任何东西。

我原本以为错误会是这样的:

>>> b[b]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'dict'

有人能在我快疯之前给我解释一下吗?

2 个回答

0

UserDict.UserDict().__hash__ 的值是 None。结合Wooble的评论,你就能明白为什么会这样。

4

根据@Wooble的建议,我查看了UserDict的实现,发现了这个:

__hash__ = None # Avoid Py3k warning

所以,问题确实是出在UserDict的实现上。

如果你真的需要使用自己的字典类型,我建议你直接从dict继承,并实现你自己的__hash__方法。或者,你也可以借助frozenset等工具,把字典转换成一个可以哈希的对象:

>>> a = UserDict.UserDict()
>>> b[frozenset(a.items())]

撰写回答