2

I am trying to understand why the code behaves the way it does

class Baz():
    def __init__(self,name):
        self.name=name


k=[Baz(i) for i in range(4)]
print([hash(i) for i in k])

print([hash(Baz(i)) for i in range(4)])

This outputs

[8736683315973, -9223363300171459831, 8736683315982, -9223363300171459822]

[8736683315991, 8736683315991, 8736683315991, 8736683315991]

I'm wondering why in the second case I get all same hashcodes

0

2 Answers 2

4

If you don't define a __hash__ method in your class Python will use the memory address for the hashing.

In the second case Bash(i) isn't needed after the hash. Python throws it away and reuses the memory for the next Bash instance, so all subsequent calls get the same hash value.

Sign up to request clarification or add additional context in comments.

1 Comment

Right this makes sense now. In the C implementation of Python this happens, same as with open(file).read() will end up automatically closing the file after the read function call since it is no longer used in memory though this doesnt happen the same in other implementations of Python so it cant be relied on
0
class Baz():
    def __init__(self,name):
        self.name=name
        print self


>>> k=[Baz(i) for i in range(4)]       
    print k
[<__main__.Baz instance at 0x7f5a010290e0>, <__main__.Baz instance at 0x7f5a01029908>, <__main__.Baz instance at 0x7f5a01028758>, <__main__.Baz instance at 0x7f5a0102e050>]`

k carry list of instances pass to class Baz with value 0, 1, 2, 3

here `self` have different object for `i` in `[hash(i) for i in k]`
if you then

print([hash(i) for i in k])
<__main__.Baz instance at 0x7f2ae9a13290>
<__main__.Baz instance at 0x7f2ae9a30908>
<__main__.Baz instance at 0x7f2ae9a300e0>
<__main__.Baz instance at 0x7f2ae9a35050>
[8738892813097, -9223363297961955184, 8738892820494, 8738892821765]

print([hash(Baz(i)) for i in range(4)])

see here, instance pass to class Baz is same. because hash uses same memory references and throws the previous memory reference for the instances.

<__main__.Baz instance at 0x7f2ae9a35290>
<__main__.Baz instance at 0x7f2ae9a35290>
<__main__.Baz instance at 0x7f2ae9a35290>
<__main__.Baz instance at 0x7f2ae9a35290>
[8738892821801, 8738892821801, 8738892821801, 8738892821801]

1 Comment

That's my question. Why is the instance same ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.