id() collisions on bound methods [was: metaclass and customization with parameters]

Robert Brewer fumanchu at amor.org
Tue Oct 5 19:50:33 EDT 2004


Andrew Durdin wrote:
> On Tue, 5 Oct 2004 18:57:49 -0300, Gustavo Niemeyer
> <niemeyer at conectiva.com> wrote:
> > 
> > That's not true. The def statement is rerun every loop, no matter
> > what parameters are used. One can check that by issuing:
> > 
> > print MyClass.method0.im_func
> > print MyClass.method1.im_func
> 
> Hmmm... If I create MyClass as above, I get the following results
> which I don't understand:
> 
> >>> mc = MyClass()
> >>> id(mc.method0)
> 9343264
> >>> id(mc.method1)
> 9343264
> >>> mc.method0
> <bound method MyClass.newmethod of <__main__.MyClass instance 
> at 0x008E93A0>>
> >>> mc.method1
> <bound method MyClass.newmethod of <__main__.MyClass instance 
> at 0x008E93A0>>
> >>> mc.method0.im_func
> <function newmethod at 0x008E7730>
> >>> mc.method1.im_func
> <function newmethod at 0x008EC0F0>
> >>> id(mc.method0.im_func)
> 9336624
> >>> id(mc.method1.im_func)
> 9355504
> 
> Why do mc.method0 and mc.method1 appear to be the same object?
> 
> Even more confusing to me is:
> 
> >>> class Foo:
> ...     def method0(self):
> ...             pass
> ...     def method1(self):
> ...             pass
> ...     def method2(self):
> ...             pass
> ...
> >>> Foo.method0
> <unbound method Foo.method0>
> >>> Foo.method1
> <unbound method Foo.method1>
> >>> Foo.method2
> <unbound method Foo.method2>
> >>> f = Foo()
> >>> id(f.method0)
> 9345304
> >>> id(f.method1)
> 9918464
> >>> id(f.method2)
> 9918464
> 
> Here f.method1 and f.method2 share the same id, which is different to
> that of f.method1...
> 
> Can anyone enlighten me as to why this happens?

..further:

>>> f = Foo()
>>> id(f.method0)
18569136
>>> id(f.method1)
18536648
>>> id(f.method2)
18536648
>>> id(f.method0)
18536648

...so the id() result is mutating somehow, even for the same object.
This is true for both old- and new-style classes, by the way, and also
holds for methods where you don't simply pass (I tried return 0,
return1, and return 2, for example function bodies)

Hmmm...


Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org



More information about the Python-list mailing list