April 27th, 2013, 07:13 PM

Partial functions
I was going through a online interactive python tutorial and I came to the section on partial functions, but I don't really understand how it works. The function below looks simple, but the answer I come up with a calculator is 66 and not 60 which is the correct answer so I thought I would ask if someone could go through this code and tell me how it works.
Code:
from functools import partial
def func(u,v,w,x):
return u*4 + v*3 + w*2 + x
p = partial(func,5,6,7)
print p(8)
April 27th, 2013, 08:06 PM

Of course we don't know which calculator buttons you pressed. Given that mp is the matrix product, 60 is the correct answer. (www.jsoftware.com)
Code:
5 6 7 8 mp 4 3 2 1
60
Maybe the partial is clearer with keyword arguments
Code:
>>> p = partial(func,u=5,v=6,w=7)
>>> p(w=8) # deliberate error
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: func() takes exactly 4 arguments (3 given)
>>> p(x=8)
60
>>>
Last edited by b49P23TIvg; April 27th, 2013 at 08:11 PM.
[code]
Code tags[/code] are essential for python code and Makefiles!