how can I use a callable object as a method
Marco Wahl
marco.wahl at novatec-gmbh.de
Thu Sep 18 07:37:05 EDT 2008
Piotr Sobolewski <NIE_DZIALA at gazeta.pl> writes:
> I would like to use a callable object as a method of a class. So, when I
> have such normal class:
>
> I want to change it to something like that:
>
> class add:
> def __call__(self, another_self):
> return another_self.version
>
> class f:
> version = 17
> a = add()
>
> f1 = f()
> print f1.a()
>
> 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). So f1.a is not a
> method. So when I do f1.a(), the implicit argument self is not passed.
>
> Q1: Am I right? Is this the problem?
> Q2: What can I do to make it work?
Use the right argument for the call.
Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> class add:
def __call__(self, another_self):
return another_self.version
... ... ... >>> class f:
version = 17
a = add()
... ... ... >>> f1 = f()
>>> f1
<__main__.f instance at 0x00A805D0>
>>> f1.a
<__main__.add instance at 0x00A80DA0>
>>> f1.a()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: __call__() takes exactly 2 arguments (1 given)
>>> f1.a(f1)
17
>>>
HTH
More information about the Python-list
mailing list