Yusuf Khaled
Yusuf Khaled

Reputation: 53

How to calculate hash of a python class object

In python3, I have a class. Like below:

class Foo:
    def __init__(self):
        self.x = 3
    def fcn(self, val):
        self.x += val

Then I instantiate objects of that class, like so:

new_obj = Foo()
new_obj2 = Foo()

Now when I hash these objects, I get different hash values. I need them to return the same hash, as they are the same objects (in theory).

Any idea how I can do this?

Upvotes: 2

Views: 3358

Answers (3)

Yusuf Khaled
Yusuf Khaled

Reputation: 53

Thank you to all who answered. You're right that instantiating a new instance of the same class object is not actually the same, as it occupies a different place in memory. What I ended up doing is similar to what @nosklo suggested.

I created a 'get_hashables' function that returned a dictionary with all the properties of the class that would constitute a unique class object, like so:

def get_hashables(self):
    return {'data': self.data, 'result': self.result}

Then my main method would take these 'hashable' variables, and hash them to produce the hash itself.

Upvotes: 2

Prune
Prune

Reputation: 77860

They are not the same object. The expression Foo() invokes the class constructor, Foo.__init__, which returns a new, unique instance of the object on each call. Your two calls return two independent objects, residing in different memory locations, each containing its own, private instance of the x attribute.

You might want to read up on Python class and instance theory.

Upvotes: 1

nosklo
nosklo

Reputation: 223092

class Foo:
    def __init__(self):
        self.x = 3
    def fcn(self, val):
        self.x += val
    def __hash__(self):
        return hash(self.x)

This will calculate the hash using self.x; That means the hash will be the same when self.x is the same. You can return anything from __hash__, but to prevent consistency bugs you should return the same hash if the objects compare equal. More about that in the docs.

Upvotes: 1

Related Questions