如何消除等于运算符的python3弃用警告? [英] How to eliminate a python3 deprecation warning for the equality operator?
问题描述
尽管标题可以解释为三个问题,但实际问题很容易描述。在Linux系统上,我安装了python 2.7.3,并希望收到有关python 3不兼容的警告。因此,我的代码段( tester.py
)看起来像:
Although the title can be interpreted as three questions, the actual problem is simple to describe. On a Linux system I have python 2.7.3 installed, and want to be warned about python 3 incompatibilities. Therefore, my code snippet (tester.py
) looks like:
#!/usr/bin/python -3
class MyClass(object):
def __eq__(self, other):
return False
当我执行此代码段时(只是为了显示问题,而不是我在项目中使用的实际代码)
When I execute this code snippet (thought to be only to show the problem, not an actual piece of code I am using in my project) as
./tester.py
我收到以下弃用警告:
./tester.py:3: DeprecationWarning: Overriding __eq__ blocks inheritance of __hash__ in 3.x
class MyClass(object):
My问题:如何更改此代码片段以摆脱警告,即使其与版本3兼容?我想以正确的方式实现相等运算符,而不仅仅是抑制警告或类似操作。
My question: How do I change this code snippet to get rid of the warning, i.e. to make it compatible to version 3? I want to implement the equality operator in the correct way, not just suppressing the warning or something similar.
推荐答案
来自文档页面,适用于Python 3.4:
From the documentation page for Python 3.4:
如果类未定义
__ eq __()
方法,它也不应该定义__ hash __()
操作;如果它定义了__ eq __()
而不是__ hash __()
,则其实例将不能用作可散列集合中的项目。如果类定义了可变对象并实现了__ eq __()
方法,则不应实现__ hash __()
,因为可散列集合的实现要求键的散列值是不可变的(如果对象的散列值更改,则它将在错误的散列存储区中)。
If a class does not define an
__eq__()
method it should not define a__hash__()
operation either; if it defines__eq__()
but not__hash__()
, its instances will not be usable as items in hashable collections. If a class defines mutable objects and implements an__eq__()
method, it should not implement__hash__()
, since the implementation of hashable collections requires that a key’s hash value is immutable (if the object’s hash value changes, it will be in the wrong hash bucket).
基本上,您需要定义 __ hash()__
函数。
Basically, you need to define a __hash()__
function.
问题在于用户定义的类,将自动定义 __ eq()__
和 __ hash()__
函数。
The problem is that for user-defined classes, the __eq()__
and __hash()__
functions are automatically defined.
x .__ hash __()
返回一个适当的值,使得x == y
暗示
x是y
和hash(x)==哈希(y)
。
x.__hash__()
returns an appropriate value such thatx == y
implies both thatx is y
andhash(x) == hash(y)
.
如果仅定义 __ eq()__
,然后将 __ hash()__
设置为返回 None
。因此,您会碰壁。
If you define just the __eq()__
, then __hash()__
is set to return None
. So you will hit the wall.
如果您不想为实现 __ hash()__
并且可以肯定地知道对象永远不会被哈希,您只需显式声明 __ hash__ = None
即可处理警告。
The simpler way out if you don't want to bother about implementing the __hash()__
and you know for certain that your object will never be hashed, you just explicitly declare __hash__ = None
which takes care of the warning.
这篇关于如何消除等于运算符的python3弃用警告?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!