Tag: oo

Python – Unique Collection Class – HashCode and Equals – (Like Java Set)

Hi readers,

I will demonstrate in this post as we do in Python to have a collection of single objects (Set), implementing the standard methods key, hashcode and equals, so that the objects are not repeated.

class MyCustomClass:
    def __init__(self, at1, at2, at3):
        self.at1 = at1
        self.at2 = at2
        self.at3 = at3
    def __key(self):
        return (self.at2)
    def __eq__(x, y):
        return x.__key() == y.__key()
    def __hash__(self):
        return hash(self.__key())

my_object_1 = MyCustomClass('1', '2', '3')
my_object_2 = MyCustomClass('4', '5', '6')
my_object_3 = MyCustomClass('7', '8', '9')
my_object_2_dup = MyCustomClass('4', '5', '6')

set_collection = set()

set_collection.add(my_object_1)
set_collection.add(my_object_2)
set_collection.add(my_object_3)
set_collection.add(my_object_2_dup)

for object in set_collection:
    print object.at2

The output of this script is:
8
2
5

Note that i added 4 objects, but only three is added because the second attribute is the Key.

See You,
Victor Jabur

Advertisements