python make an object hashable

Solutions on MaxInterview for python make an object hashable by the best coders in the world

showing results for - "python make an object hashable"
Asma
24 Apr 2017
1class Hero:
2    def __init__(self, name, age):
3        self.name = name
4        self.age = age
5
6    def __str__(self):
7        return self.name + str(self.age)
8
9    def __hash__(self):
10        print(hash(str(self)))
11        return hash(str(self))
12
13    def __eq__(self,other):
14        return self.name == other.name and self.age== other.age
15
16
17
18heroes = set()
19heroes.add(Hero('Zina Portnova', 16)) # gets hash -8926039986155829407
20print(len(heroes)) # gets 1
21
22heroes.add(Hero('Lara Miheenko', 17)) # gets hash -2822451113328084695
23print(len(heroes)) # gets 2
24
25heroes.add(Hero('Zina Portnova', 16)) # gets hash -8926039986155829407
26print(len(heroes)) # gets 2 
27