2013-03-20 3 views
3

Voici un excerpt from Python's docs re id() build-in function:Python id (obj) change ad hoc

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

Alors ... comment se fait-il des changements dans l'exemple suivant?

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

Répondre

0

a.f traduit à quelque chose comme f.__get__(a, A)f est l'objet de la fonction "d'origine". De cette façon, la fonction génère un wrapper, et ce wrapper est généré à chaque appel.

a.f.im_func renvoie à la fonction originale, dont les id() ne devraient jamais changer.

Mais dans le question referenced above le problème est adressé encore plus concis.