python(哈希性hashable和不可改變性imutable)


hashable和imutable

翻譯自官方文檔:

1.什么是可哈希的(hashable)不該改變的(imutable)?

如果一個對象在自己的生命周期中有一哈希值(hash value)是不可改變的,那么它就是可哈希的(hashable)的,因為這些數據結構內置了哈希值,每個可哈希的對象都內置了__hash__方法,所以可哈希的對象可以通過哈希值進行對比,也可以作為字典的鍵值和作為set函數的參數。所有python中所有不可改變的的對象(imutable objects)都是可哈希的,比如字符串,元組,也就是說可改變的容器如字典,列表不可哈希(unhashable)。我們用戶所定義的類的實例對象默認是可哈希的(hashable),它們都是唯一的,而hash值也就是它們的id()。

哈希(散列?whatever)是一個將大體量數據轉化為很小數據的過程,甚至可以僅僅是一個數字,以便我們可以用在固定的時間復雜度下查詢它,所以,哈希對高效的算法和數據結構很重要。

不可改變性是指一些對象在被創建之后不會因為某些方式改變,特別是針對任何可以改變哈希對象的哈希值的方式。

兩者相聯系是因為哈希鍵值一定是不可改變的,所以它們對應的哈希鍵值也不改變。如果允許它們改變,,那么它們在數據結構如哈希表中的存儲位置也會改變,因此會與哈希的概念違背,效率會大打折扣。

官方文檔: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(tuple等), 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 (except with themselves), and their hash value is their id().

來自stackoverflow的高票數回答:

Hashing is the process of converting some large amount of data into a much smaller amount (typically a single integer) in a repeatable way so that it can be looked up in a table in constant-time (O(1)), which is important for high-performance algorithms and data structures.

Immutability is the idea that an object will not change in some important way after it has been created, especially in any way that might change the hash value of that object.

The two ideas are related because objects which are used as hash keys must typically be immutable so their hash value doesn't change.  If it was allowed to change then the location of that object in a data structure such as a hashtable would change and then the whole purpose of hashing for efficiency is defeated.

To really grasp the idea you should try to implement your own hashtable in a language like C/C++, or read the Java implementation of the HashMap class.

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM