substitution of a method by a callable object

George Sakkis george.sakkis at gmail.com
Wed Oct 22 13:40:45 EDT 2008


On Oct 22, 12:13 pm, netimen <neti... at gmail.com> wrote:

> Can I substitute a method of a class by a callable object (not a
> function)? I can very easy insert my function in a class as a method,
> but an object - can't.
>
> I have the following:
>
> class Foo(object):
>     pass
>
> class Obj(object):
>     def __call__(self, obj_self):
>         print 'Obj'
>
> def func(self):
>     print 'func'
>
> f = Foo()
> Foo.meth = func
> f.meth() # all goes OK
> Foo.meth = Obj()
> f.meth() # I get TypeError: __call__() takes exactly 2 arguments (1
> given)

You have to wrap it as an (unbound) instance method explicitly:

from types import MethodType
Foo.meth = MethodType(Obj(), None, Foo)
f.meth()

For normal functions this seems to be done implicitly (of course you
can do it explicitly if you want):

>>> Foo.meth = func
>>> print Foo.meth
<unbound method Foo.func>

George



More information about the Python-list mailing list