I have a class called Transaction
, which contains multiple attributes. If any of these attributes match, then i want those transactions to be treated as duplicate transactions and hence do not want to store duplicates in a set.
class Transaction:
def __init__(self, a, b):
self.a = a
self.b = b
def __eq__(self, other):
if not isinstance(other, Transaction):
return NotImplemented
return self.a == other.a or self.b == other.b
def __hash__(self):
# TODO
I learnt that it is important to implement both __eq__
as well as __hash__
if we want to avoid duplicates while inserting in a set. Also, if A == B, then their hashes should also match as per the contract.
How can i implement __hash__
in this case, so that if i try to insert a transaction into the set, then it is rejected if it contains repeated value of either attribute 'a' or 'b'.
Thanks in advance!