Python id(obj)改变了ad-hoc

时间:2013-03-20 10:49:44

标签: python built-in objectid

这是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.

那么......在下面的例子中它是如何变化的?

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

1 个答案:

答案 0 :(得分:0)

a.f转换为f.__get__(a, A),其中f是“原始”功能对象。这样,该函数生成一个包装器,并在每次调用时生成此包装器。

a.f.im_func引用回原始函数,其id()永远不会改变。

但在question referenced above中,问题更加简洁。