bizarre id() results

Diez B. Roggisch deets at nospam.web.de
Thu Dec 15 16:35:22 EST 2005


> # ok, both methods work and give the expected results
> # so i presume they are different methods.
> 
>>>>id(a.m1)
> 
> 9202984
> 
>>>>id(a.m2)
> 
> 9202984
> 
>>>>id(a.m1)==id(a.m2)
> 
> True
> # Huh? They seem to be the same. 

What you observe is rooted in two things:

 - python objects bound methods are created on demand. Consider this
example:


class Foo:
   def m(self):
      pass

f = Foo()
m1 = f.m
m2 = f.m

print id(m1), id(m2)


The reason is that the method iteself is bound to the instance - this
creates a bound method each time.

The other thing is that this bound method instances are immediaty
garbage collected when you don't keep a reference. That results in the
same address being used for subsequent bound method instantiations:

print id(f.m)
print id(f.m)


results in the same id being printed. It doesn't matter if you use m1,
m2 instead, as in your example.

HTH,

Diez



More information about the Python-list mailing list