substitution of a method by a callable object

netimen netimen at gmail.com
Wed Oct 22 23:58:28 CEST 2008


On 23 окт, 00:34, Terry Reedy <tjre... at udel.edu> wrote:
> George Sakkis wrote:
> > 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:
>
> Nope.  As the error message says, the method was called with nothing
> provided to be bound to the extraneous parameter obj_self.  Either
> provide an arg, such as with f.meth(1), *or* delete obj_self and 'Obj'
> is printed, with both 2.5 and 3.0.

OK, I have implemented Bruno Desthuilliers example. But there is
another question: can I having a method determine if it is an instance
of given class. So:

class Obj(object):
      __name__ = "Obj" # for Method.__repr_

     def __call__(self, obj_self):
         print 'Obj'

     def __get__(self, instance, cls):
         return MethodType(self, instance, cls)

class Foo(object):
    pass

Foo.meth = Obj()

## in some another place of code
if isinstance(Foo.meth, Obj): # doesn't work because type(Foo.meth) is
now 'instancemethod'
   ...

Can I determine that?



More information about the Python-list mailing list