python tips: a class as key dict

Python's dict implemented by hash, hash solution to the conflict is a secondary probe method. Like elements will form a hash value list. Therefore, when looking dict key, acquired first hash value, directly linked list header; then equal to key value in the lookup list.

For instance it can be used as a target value of the dict key, and two general methods need to implement __hash__ __eq__.

Examples of the class does not implement the method is not always equal __eq__ (always different reference)

 1 class A:
 2     def __hash__(self):
 3         return 2
 4 
 5 a = A()
 6 b = A()
 7 d = {a:0}
 8 if b in d:
 9     print(d[b])
10 else:
11     print("b is not in d")

Output

1 b is not in d

Examples of possible key

 1 class A:
 2     def __hash__(self):
 3         return 2
 4     
 5     def __eq__(self, other):
 6         return True
 7 
 8 a = A()
 9 b = A()
10 d = {a:0}
11 if b in d:
12     print(d[b])
13 else:
14     print("b is not in d")

Output

1 0

to sum up:

1. As to the key dict, need to be able find a hash value (key immutable object), a need for comparison (whether or not equal)

For class 2, the instance of the need to achieve a __hash__ request hash, the need to achieve equality comparison __eq __ (default reference comparison, reference is always different in different instances)

 

Guess you like

Origin www.cnblogs.com/luoheng23/p/11018813.html