Python3调用__hash__()触发TypeError:'NoneType'对象不可调用问题
Python2迁移至Python3时__hash__方法TypeError异常问题解析
问题产生原因
- Python 2的规则是:若自定义类仅显式实现
__eq__()而未实现__hash__(),会默认继承父类的__hash__()方法,因此你的代码在Python 2中可以正常运行。 - Python 3修改了哈希方法的默认规则:如果一个类显式定义了
__eq__()且没有显式定义__hash__(),解释器会自动将该类的__hash__属性设置为None,这就导致你调用a.__hash__()时触发NoneType不可调用的TypeError。
解决方案
如果你需要子类A直接复用基类Base的__hash__()逻辑,有两种常用实现方式:
方式1:显式指定继承父类的__hash__
直接在子类A的作用域内绑定父类的哈希方法即可:
class A(Base): def __init__(self, _id): Base.__init__(self, _id) self._id = _id def __eq__(self, other): return self._id == other._id def __ne__(self, other): return not self.__eq__(other) # 显式指定继承基类的__hash__方法 __hash__ = Base.__hash__
方式2:在子类中重写__hash__(),调用父类实现
如果后续有扩展子类哈希逻辑的需求,可以直接重写方法并调用父类实现:
class A(Base): def __init__(self, _id): Base.__init__(self, _id) self._id = _id def __eq__(self, other): return self._id == other._id def __ne__(self, other): return not self.__eq__(other) def __hash__(self): return super().__hash__()
内容的提问来源于stack exchange,提问作者Raymond Reddington
相关产品推荐
相关产品推荐

