UnboundMethodType and MethodType
Scott David Daniels
scott.daniels at acm.org
Wed Feb 8 10:20:35 EST 2006
Kent Johnson wrote:
> Kirk McDonald wrote:
...
>> >>> id(B.bar)
>> -1211888788
>> >>> id(b.bar)
>> -1211888788
>>
>> It's the same function, whether it's bound or not....
>
> No, it's not the same function. You got the same id because you didn't
> bind B.bar and b.bar to anything so the id was reused.
>
> >>> class B(object):
> ... def bar(self): pass
> ...
> >>> Bbar = B.bar
> >>> bbar = B().bar
> >>> Bbar
> <unbound method B.bar>
> >>> bbar
> <bound method B.bar of <__main__.B object at 0x008759B0>>
> >>> id(Bbar)
> 10751312
> >>> id(bbar)
> 10736624
> >>> Bbar is bbar
> False
>
> Kent
To elaborate on this, once 'id' is called, you drop the reference.
This allows quite surprising things like:
>>> id(7**8) == id(8**7)
True
>>> a, b = 7**8, 8**7
>>> id(a) == id(b) # this time there are other references to a and b
False
If you wanted to test the original code for identity match:
>>> B.bar is B().bar
False
is the appropriate test (the 'is' test holds the identities through
the comparison).
By the by, this is tricky stuff, nobody should expect to understand
it thoroughly without both study and testing.
--Scott David Daniels
scott.daniels at acm.org
More information about the Python-list
mailing list