substitution of a method by a callable object
Terry Reedy
tjreedy at udel.edu
Wed Oct 22 13:19:08 EDT 2008
netimen 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.
Yes you can and did.
> 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)
So either remove the unused obj_self parameter from __call__ or pass
something -- anything -- to be bound to it.
f.meth(1) for instance, works fime (in 3.0 at least)
More information about the Python-list
mailing list