bizarre id() results

Fredrik Lundh fredrik at pythonware.com
Thu Dec 15 16:32:56 EST 2005


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.

try running this script:

class bound_simulator:
    def __init__(self, method):
        self.method = method
        print "alloc", method, id(self)
    def __del__(self):
        print "release", self.method, id(self)

class instance_simulator:
    def __getattr__(self, method):
        return bound_simulator(method)

i = instance_simulator()

print id(i.m1)
print id(i.m2)
print id(i.m1) == id(i.m2)
print i.m1 is i.m2

and see if you can figure out what's going on here.

</F>






More information about the Python-list mailing list