views:

55

answers:

5

All,

def a(p):
    return p+1

def b(func, p):
    return func(p)

b(a,10)   # 11

here I do not want the result "11" actually, what I want is a function object with the parameter has been binded, let's name it c.

when I use c() or something alike, it will give me the result 11, possible?

Thanks!

+3  A: 

The only way to do that, is to wrap it in a lambda:

c = lambda : b(a,10)
c() # 11

Though if you're going to name it anyway, that doesn't really buy you anything compared to

def c():
  b(a,10)
sepp2k
thanks, actually I will have a list of b(a,x), I want use [x() for x in list] to get the result in a go.
user478514
+1  A: 

Though I am not sure of the use, Use lambda:

>>> def a(p): return p+1
... 
>>> def b(func, p):
...     g = lambda p: func(p) 
...     return g
... 
>>> 
>>> b(a, 4)
<function <lambda> at 0x100430488>
>>> k = b(a, 4)
>>> k(5)
6
pyfunc
A: 

You can create another function that calls the your function with the parameter that you want.

def old_function(x,y):
    return x+y

def bound_parameter_function(x):
    return old_function(x,10)

Of course, if you need to create such functions on the fly, you can write another function that does the job for you:

def parameter_bound(f, parm_to_bind):
    def ret(y):
        return f(parm_to_bind,y)
     return ret

new_func=parameter_bound(old_function,10)
new_func(1)
MAK
+7  A: 

you can also use the functools module


import functools

def add(a,b):
    return a+b

>> add(4,6)

10
>> plus7=functools.partial(add,7)
>>plus7(9)
16

 
mossplix
+4  A: 

The functools module provides the partial function which can give you curried functions:

import functools

def a(p):
    return p+1

def b(func, p):
    return functools.partial(func, p)

c = b(a,10)
print c() # >>  11

It can be used to apply some parameters to functions, and leave the rest to be supplied:

def add(a,b):
    return a+b

add2 = functools.partial(add, 2)
print add2(10)  # >> 12
Ned Batchelder
can you explain why 2 and 10 can be separated?
user478514
functools.partial takes a function and some number of arguments, then returns a function that takes the rest of the arguments.
Ned Batchelder