Skip to content

Commit 45bc384

Browse files
committed
Hashable
1 parent b699970 commit 45bc384

File tree

1 file changed

+19
-2
lines changed

1 file changed

+19
-2
lines changed

README.md

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -636,13 +636,30 @@ class Employee(Person):
636636
```
637637

638638
### Comparable
639+
**If eq() method is not overriden, it returns `id(self) == id(other)`, which is the same as `self is other`, meaning all objects compare not equal by default.**
640+
639641
```python
640642
class MyComparable:
641643
def __init__(self, a):
642644
self.a = a
643645
def __eq__(self, other):
644-
# If not defined it returns id(self) == id(other).
645-
if isinstance(other, MyComparable):
646+
if isinstance(other, type(self)):
647+
return self.a == other.a
648+
return False
649+
```
650+
651+
### Hashable
652+
**Hashable object needs both hash() and eq() methods and it's hash value should not change. Objects that compare equal must have the same hash value, meaning default hash() that returns `id(self)` will not do. That is why Python automatically makes classes unhashable if you only implement eq().**
653+
654+
```python
655+
class MyHashable:
656+
def __init__(self, a):
657+
self.__a = a
658+
@property
659+
def a(self):
660+
return self.__a
661+
def __eq__(self, other):
662+
if isinstance(other, type(self)):
646663
return self.a == other.a
647664
return False
648665
def __hash__(self):

0 commit comments

Comments
 (0)