question about the id()
Bengt Richter
bokr at oz.net
Mon May 16 01:14:31 EDT 2005
On Mon, 16 May 2005 11:28:31 +0800, "kyo guan" <kyoguan at gmail.com> wrote:
>HI Skip:
>
> I want to check is there any change in the instance 's methods.
>>>> a=A()
>>>> a2=A()
>>>> a.f == a2.f
>False
>>>> a.f is a2.f
>False
>>>> a.f is a.f
>False
>>>>
> If the instance methods are create on-the-fly, how to do that? Thanks.
You have to define exactly what you mean by "the instance's methods" first ;-)
a.f is an expression that when evaluated creates a bound method according to
the rules of doing that. You can check what function was found for creating
this bound method using the .im_func attribute -- i.e. a.f.im_func -- but that
is only valid for that particular bound method. A bound method is a first class
object that you can pass around or assign, so the function you might get from
a fresh a.f might differ from a previous a.f, e.g.,
>>> class A(object):
... def f(self): return 'f1'
...
>>> a=A()
>>> a2=A()
>>> a.f.im_func is a2.f.im_func
True
Now save the bound method a.f
>>> af = a.f
And change the class A method
>>> A.f = lambda self: 'f2'
Both a and a2 dynamically create bound methods based on the new method (lambda above)
so the functions are actually the same identical one
>>> a.f.im_func is a2.f.im_func
True
But the bound method we saved by binding it to af still is bound to the old method function,
so a new dynamically created one is not the same:
>>> af.im_func is a2.f.im_func
False
>>> af.im_func
<function f at 0x02FA3CDC>
>>> a.f.im_func
<function <lambda> at 0x02F99B1C>
>>> a2.f.im_func
<function <lambda> at 0x02F99B1C>
The .im_func function id's are shown in hex through the repr above. I.e., compare with:
>>> '0x%08X' % id(a2.f.im_func)
'0x02F99B1C'
>>> '0x%08X' % id(af.im_func)
'0x02FA3CDC'
HTH
Regards,
Bengt Richter
More information about the Python-list
mailing list