3

Here's an excerpt from Python's docs re id() build-in function:

== id(object) ==
Return the “identity” of an object. This is an integer (or long integer) which is
guaranteed to be unique and constant for this object during its lifetime.
Two objects with non-overlapping lifetimes may have the same id() value.

CPython implementation detail: This is the address of the object in memory.

So... how come it changes in the following example?

>>> class A(object):
...   def f(self):
...     return True
... 
>>> a=A()
>>> id(a.f)
Out[21]: 62105784L
>>> id(a.f)
Out[22]: 62105784L
>>> b=[]
>>> b.append(a.f)
>>> id(a.f)
Out[25]: 50048528L
Jonathan Livni
  • 101,334
  • 104
  • 266
  • 359

1 Answers1

0

a.f translates to something like f.__get__(a, A) where fis the "original" function object. This way, the function generates a wrapper, and this wrapper is generated on every call.

a.f.im_func references back to the original function, whose id() should never change.

But in the question referenced above the issue is addressed even more concise.

Community
  • 1
  • 1
glglgl
  • 89,107
  • 13
  • 149
  • 217