Dynamic method

Daniel millerdev at gmail.com
Mon Jul 16 23:30:32 CEST 2007


Bruno Desthuilliers wrote:
>
> > Another way is to use the 'types' module:
>
> True - and that's somewhat cleaner since it doesn't expose the internals
> of the descriptor protocol. OTHO, it can lead to strange results with
> callables not implementing the descriptor protocol:

<snip>

Actually, the result is not "strange" at all if you understand what's
going. The reason you got an exception is because your __call__()
method only takes a single argument (the implicit self argument, which
is the instance of MyCallable). However, if you define it with two
arguments it works just fine:

>>> class MyCallable(object):
...     def __call__(self, inst):
...         print self, inst
...
>>> class Foo(object):
...     pass
...
>>> fun = MyCallable()
>>> f = Foo()
>>> f.fun = types.MethodType(fun, f, Foo)
>>> f.fun()
<__main__.MyCallable object at 0x648d0> <__main__.Foo object at
0x64810>
>>>

~ Daniel




More information about the Python-list mailing list