python 中倒是什么事可哈希的意思那?

可哈希对象

python中的hashable(可哈希的)是什么意思

不严谨但易懂的解释:

一个对象在其生命周期内,如果保持不变,就是hashable(可哈希的)。

hashable ≈ imutable     可哈希 ≈ 不可变

在Python中:

list、set和dictionary 都是可改变的,比如可以通过list.append(),set.remove(),dict['key'] = value对其进行修改,所以它们都是不可哈希的;

而tuple和string是不可变的,只可以做复制或者切片等操作,所以它们就是可哈希的。

官方解释:

An object is hashable if it has a hash value which never changes during its lifetime (it needs a __hash__() method), and can be compared to other objects (it needs an __eq__() or __cmp__() method). Hashable objects which compare equal must have the same hash value.

Hashability makes an object usable as a dictionary key and a set member, because these data structures use the hash value internally.

All of Python’s immutable built-in objects are hashable, while no mutable containers (such as lists or dictionaries) are. Objects which are instances of user-defined classes are hashable by default; they all compare unequal, and their hash value is their id().

大致翻译一下:

如果一个对象在其生命周期内,其哈希值从未改变(这需要一个__hash__()方法),并且可以与其他对象进行比较(这需要一个__eq__()或__cmp__()方法),那么这个对象就是可哈希的。哈希对象的相等意味着其哈希值的相等。

哈希性使得对象可以用作dictionary键和set成员,因为这些数据结构在内部使用了哈希值。

Python的所有不可变的内置对象都是可hashable的,但可变容器(如列表或字典)并非如此。对于用户定义的类的实例,默认情况下是可哈希的;它们都是不相等的,并且它们的哈希值都是id()。

hashable

如果一个对象是可哈希的,那么它就有一个在其生命周期中都不会改变的哈希值,它会有一个__hash__()方法,它要能够和其他对象比较(需要__eq__()方法或__cmp__()方法)。可哈希对象相同要求哈希值相同。

不可哈希

list, set, dict

可哈希

数值,字符串,boolean

对象可不可hash?

class A:
    def __init__(self): pass a = A() print hash(a) 

实验发现对象是可哈希的,为啥呢?因为所有对象都继承自object,而object有__hash__方法。bingo!

等等!不是说python一切皆对象么?

>>> issubclass(int, object)
True
>>> issubclass(list, object)
True

抱着试一试的态度,我查看了一下list,发现也有__hash__方法。但是list不是不可哈希的么??于是我们打印出__hash__看一看。

print object.__hash__
# <slot wrapper '__hash__' of 'object' objects>

print int.__hash__
# <slot wrapper '__hash__' of 'int' objects>

print list.__hash__ # None 

哈哈,这下清楚了,虽然list也有__hash__属性,但是是None,同样dict和set的__hash__也是None。想知道一个对象是不是可哈希,只要看__hash__是不是None。
不要相信我,相信自己的代码

class A:
    def __init__(self): self.__hash__ = None a = A() print hash(a) 

现在a对象已经不可哈希了。

转发https://www.jianshu.com/p/1a05bd66936a

https://blog.csdn.net/qq_17753903/article/details/85345996

猜你喜欢

转载自www.cnblogs.com/harry-han/p/10801264.html