Why aren't bound instance methods in python reference equal?
Asked Answered
P

1

9
>>> class foo(object):
...     def test(s):
...         pass
...
>>> a=foo()
>>> a.test is a.test
False
>>> print a.test
<bound method foo.test of <__main__.foo object at 0x1962b90>>
>>> print a.test
<bound method foo.test of <__main__.foo object at 0x1962b90>>
>>> hash(a.test)
28808
>>> hash(a.test)
28808
>>> id(a.test)
27940656
>>> id(a.test)
27940656
>>> b = a.test
>>> b is b
True
Principe answered 21/3, 2011 at 22:43 Comment(0)
K
7

They're bound at runtime; accessing the attribute on the object rebinds the method anew each time. The reason they're different when you put both on the same line is that the first method hasn't been released by the time the second is bound.

Katydid answered 21/3, 2011 at 22:52 Comment(2)
Put differently, the id seems the same each time because the previous instance is gc'd immediately after the result was printed, and memory management in that particular version of CPython happens to be predictable enough to put the next object in the same place.Faeroese
Haha it never occurred to me the GC would relocate it at the same addr. Thanks all this makes sense.Principe

© 2022 - 2024 — McMap. All rights reserved.