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()


for object in set_collection:
    print object.at2

The output of this script is:

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

See You,
Victor Jabur


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s