目录:Python 使用 __hash__ 和 __eq__ 的问题Python 类中特殊方法 __eq__ 和 __hash__ 的关系Python 使用 __hash__ 和 __eq__ 的问题代码版本:3.6.3文档版本:3.6.6object.__hash__(self) Called by built-in function hash() and for op
目录
Python使用__hash__和__eq__的问题
Python类中特殊方法__eq__和__hash__关系
Python使用__hash__和__eq__的问题
代码版本3.6.3
文档版本:3.6.6
object.__hash__(self)
Called by built-in function hash() and for operations on members of hashed collections including set, frozenset, and dict.
__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).
User-defined classes have __eq__() and __hash__() methods by default; with them, all objects compare unequal (except with themselves) and x.__hash__() returns an appropriate value such that x == y implies both that x is y and hash(x) == hash(y).
用户定义的类默认都有__eq__()和__hash__()方法,这是从object继承的,如果你不重写任何一个,那么对这个类的两个实例x,y来说,x is y ,x == y , hash(x) == hash(y)会同时成立/不成立,即只有在x就是y的时候成立。
A class that overrides __eq__() and does not define __hash__() will have its __hash__()implicitly set to None. When the __hash__() method of a class is None, instances of the class will raise an appropriate TypeError when a program attempts to retrieve their hash value, and will also be correctly identified as unhashable when checking isinstance(obj, collections.abc.Hashable).
# 直接安装不成功 pip install collections2 才行
# collections2==0.3.0 A set of improved data types inspired by the standard library's collections module.
import collections
class A:
def __eq__(self, other):
pass
class B:
pass
a = A()
b = B()
print(isinstance(a, collections.abc.Hashable)) # False
print(isinstance(b, collections.abc.Hashable)) # True
If a class that overrides __eq__() needs to retain the implementation of __hash__() from a parent class, the interpreter must be told this explicitly by setting __hash__ =<ParentClass>.__hash__.
If a class that does not override __eq__() wishes to suppress hash support, it should include __hash__ = None in the class definition. A class which defines its own __hash__() that explicitly raises a TypeError would be incorrectly identified as hashable by an isinstance(obj, collections.abc.Hashable) call.
import collections
class A:
def __eq__(self, other):
pass
__hash__ = object.__hash__
class B:
def __hash__(self):
raise TypeError('There is an error!')
a = A()
b = B()
print(isinstance(a, collections.abc.Hashable))
print(isinstance(b, collections.abc.Hashable))
hash(b)
# 结果:
# True
# True
# ...line 12, in __hash__...
# TypeError: There is an error!
文档位置:3.6.6 object.__hash__
Python类中特殊方法__eq__和__hash__关系
class Point(object):
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return repr((self.id, self.x, self.y))
def __eq__(self, other):
return self.x == other.y and self.y == self.y
def __hash__(self):
return hash((self.x, self.y))
当对两个点的实例进行值的比较时,比如p1=Point(1,1) p2=Point(1,2),判断p1==p2时__eq__()会被调用,用以判断两个实例是否相等。在上述代码中定义了只要x和y的坐标相同,两个点相等。需要注意,__eq__()对is不生效,==是比较的值,而is比较的是引用,也就是内存地址。举个例子,p1=Point(1,1) p2=Point(1,1),p1==p2为True,p1 is p2为False,只有p1 is p1为True。
目录:Python 使用 __hash__ 和 __eq__ 的问题Python 类中特殊方法 __eq__ 和 __hash__ 的关系Python 使用 __hash__ 和 __eq__ 的问题代码版本:3.6.3文档版本:3.6.6object.__hash__(self) Called by built-in function hash() and for op
目录
Python使用__hash__和__eq__的问题
Python类中特殊方法__eq__和__hash__关系
Python使用__hash__和__eq__的问题
代码版本3.6.3
文档版本:3.6.6
object.__hash__(self)
Called by built-in function hash() and for operations on members of hashed collections including set, frozenset, and dict.
__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).
User-defined classes have __eq__() and __hash__() methods by default; with them, all objects compare unequal (except with themselves) and x.__hash__() returns an appropriate value such that x == y implies both that x is y and hash(x) == hash(y).
用户定义的类默认都有__eq__()和__hash__()方法,这是从object继承的,如果你不重写任何一个,那么对这个类的两个实例x,y来说,x is y ,x == y , hash(x) == hash(y)会同时成立/不成立,即只有在x就是y的时候成立。
A class that overrides __eq__() and does not define __hash__() will have its __hash__()implicitly set to None. When the __hash__() method of a class is None, instances of the class will raise an appropriate TypeError when a program attempts to retrieve their hash value, and will also be correctly identified as unhashable when checking isinstance(obj, collections.abc.Hashable).
# 直接安装不成功 pip install collections2 才行
# collections2==0.3.0 A set of improved data types inspired by the standard library's collections module.
import collections
class A:
def __eq__(self, other):
pass
class B:
pass
a = A()
b = B()
print(isinstance(a, collections.abc.Hashable)) # False
print(isinstance(b, collections.abc.Hashable)) # True
If a class that overrides __eq__() needs to retain the implementation of __hash__() from a parent class, the interpreter must be told this explicitly by setting __hash__ =<ParentClass>.__hash__.
If a class that does not override __eq__() wishes to suppress hash support, it should include __hash__ = None in the class definition. A class which defines its own __hash__() that explicitly raises a TypeError would be incorrectly identified as hashable by an isinstance(obj, collections.abc.Hashable) call.
import collections
class A:
def __eq__(self, other):
pass
__hash__ = object.__hash__
class B:
def __hash__(self):
raise TypeError('There is an error!')
a = A()
b = B()
print(isinstance(a, collections.abc.Hashable))
print(isinstance(b, collections.abc.Hashable))
hash(b)
# 结果:
# True
# True
# ...line 12, in __hash__...
# TypeError: There is an error!
文档位置:3.6.6 object.__hash__
Python类中特殊方法__eq__和__hash__关系
class Point(object):
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return repr((self.id, self.x, self.y))
def __eq__(self, other):
return self.x == other.y and self.y == self.y
def __hash__(self):
return hash((self.x, self.y))
当对两个点的实例进行值的比较时,比如p1=Point(1,1) p2=Point(1,2),判断p1==p2时__eq__()会被调用,用以判断两个实例是否相等。在上述代码中定义了只要x和y的坐标相同,两个点相等。需要注意,__eq__()对is不生效,==是比较的值,而is比较的是引用,也就是内存地址。举个例子,p1=Point(1,1) p2=Point(1,1),p1==p2为True,p1 is p2为False,只有p1 is p1为True。