bizarre id() results

Chris Lambacher chris at kateandchris.net
Thu Dec 15 16:48:12 EST 2005


a.m1 returns a bound method which gets freed before you try checking a.m2,
which ends up  getting the same peice of memory.  If you save a reference to
the bound methods, they are forced to have separate objects.

>>> class A:
...  def m1(self): print "m1"
...  def m2(self): print "m2"
... 
>>> a = A()
>>> a.m1()
m1
>>> a.m2()
m2
>>> id(a.m1)
25402184
>>> id(a.m2)
25402184
>>> b = a.m1
>>> c = a.m2
>>> id(b)
25402184
>>> id(c)
25541848


-Chris

On Thu, Dec 15, 2005 at 02:19:15PM -0700, Stuart McGraw wrote:
> The following was cut and pasted exactly (except for the 
> # lines which I added after the fact) from an interactive python 
> session in a Window 2000 cmd.exe window. 
>  
> Can somebody please explain to me what the heck is 
> going on?!?!  
> 
> Python 2.4.2 (#67, Sep 28 2005, 12:41:11) [MSC v.1310 32 bit (Intel)] on win32
> Type "help", "copyright", "credits" or "license" for more information.
> >>> class A:
> ...  def m1(self): print "m1"
> ...  def m2(self): print "m2"
> ...
> >>> a = A()
> >>> a.m1()
> m1
> >>> a.m2()
> m2
> # 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. 
> >>> a.m1 is a.m2
> False
> # But not the same...
> >>> a.m1
> <bound method A.m1 of <__main__.A instance at 0x00923B98>>
> >>> a.m2
> <bound method A.m2 of <__main__.A instance at 0x00923B98>>
> # Let's look at them in hex...
> >>> hex(id(a.m1))
> '0x8c6d28'
> >>> hex(id(a.m2))
> '0x8e7b48'
> # Now they are different.  0x8c6d28->9202984, 0x8e7b48->9337672
> >>> id(a.m1)
> 9337672
> >>> id(a.m2)
> 9337672
> # Now they are both equal to the second one.
> >>> hex(id(a.m1))
> '0x8e7b48'
> >>> hex(id(a.m2))
> '0x8e7b48'
> # in hex too.
> >>> id
> <built-in function id>
> >>> hex
> <built-in function hex>
> # just double checking!
> 
> Why???  This is so bizarre I'm sure I am doing something
> really stupid.
> 
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list



More information about the Python-list mailing list