Function question

Bengt Richter bokr at oz.net
Mon Apr 8 04:54:30 EDT 2002


On Sun, 7 Apr 2002 23:55:47 -0500, "John" <nobody at nobody.com> wrote:

>
>Hi I have a question:
>
>Let's say there is a function with two arguments.
>def add(a,b): return a+b
>
>What I want to do is:
>I want to get 'a' dynamically..
>But once a value is decided, I want a separate function (say, new_add) that
>does
>new_add(b) (equals to) add(a,b)
>
>That is, I want the function definition to be dynamic.
>
>Would that be possible? Any comment would be greatly appreciated.
>
If you want to store initialized state to be used by a function,
one way is to define a class whose constructor takes the initial
parameters and stores them (or state computed based on them, etc.)
in the data of the created instance. If you supply a __call__ method,
you can call it with syntax that looks just like a function call using
the instance as the function:

 >>> class AddK:
 ...     def __init__(self, k):
 ...         self.k = k
 ...     def __call__(self, v):
 ...         return self.k + v
 ...
 >>> add2 = AddK(2)
 >>> addten = AddK(10)
 >>> add2(5)
 7
 >>> add2(3)
 5
 >>> addten(5)
 15

I find this simple and clear, and I would expect it
to be faster than unoptimized generalized currying as
described in another post (though it is nice).
The function-returning function in another post might
be about the same speed. You'd have to test if speed is
a concern.

The nice thing about the object approach is that you have
an open door to further customization of your computing gizmo.
You can add methods to query it, modify it, have it present
itself as string, as true or false, etc. etc.

Regards,
Bengt Richter



More information about the Python-list mailing list