metaclass and customization with parameters

Jack Diederich jack at performancedrivers.com
Tue Oct 5 19:54:16 EDT 2004


On Wed, Oct 06, 2004 at 10:35:01AM +1100, 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>>
> 
> Why do mc.method0 and mc.method1 appear to be the same object?

Read it more closely, they are just saying they are bound methods of the same
object instance, not that they are the same object themselves.

> 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?

A temporary object is being made when you lookup 'method2' in 'f'
Try assigning the value to a local variable and then running id() on those
local variables.  The id()s should remain stable. What you are seeing is 
just a fluke, the same id gets used and then scrapped and then used again.

-Jack



More information about the Python-list mailing list