how can I use a callable object as a method

Hrvoje Niksic hniksic at xemacs.org
Thu Sep 18 08:04:50 EDT 2008


Piotr Sobolewski <NIE_DZIALA at gazeta.pl> writes:

> However, the second version does not work. I think I understand
> why. That's because "a" inside f1 is not a function (but an object).

An object that defines __call__ is perfectly usable as a function.
Your problem is that it doesn't know how to convert itself to a
method, so that f1.a() knows how to pass f1 as another_self to
add.__call__.  To do that, add needs to be a bit smarter:

>>> class add(object):
...   def __call__(self, another_self):
...     return another_self.version
...   def __get__(self, obj, type=None):
...     return lambda: self(obj)
...
>>> class f(object):
...   version = 17
...   a = add()
...
>>> f1 = f()
>>> f1.a()
17

If you can't modify add, you can probably use an adaptor that defines
__get__ in a similar way.



More information about the Python-list mailing list