开发者

How to associate parameters with a function object?

I am new to python and I find the "even functions are objects" thing really cool, so I was just playing with functions in the PyShell. The followi开发者_JAVA技巧ng code worked fine.

def add_num(a,b):
  c = a + b
  return c

x = add_num
x(5,2)

I was wondering whether we can store the parameters when we are assigning x = add_num. So that whenever we call x() it adds a and b (here 5 and 2) and returns the result. x = add_num(5,2) won't work since add_num(5,2) actually calls the function and returns 7.


The partial function in the functools module (documentation) can create a new function object behaving like you want.

import functools

def add_num(a, b):
    c = a + b
    return c

x = functools.partial(add_num, 5, 2)
print(x()) # prints 7

You can also specify only one argument, and provide the other one when calling the "partial" function:

y = functools.partial(add_num, 5)
print(y(6)) # prints 11

It works for keyword arguments too:

z = functools.partial(add_num, b=5)
print(z(10)) # prints 15

As suggested in the comments, another option is to use a lambda expression (documentation), which is just a shorthand for creating a new function.

f = lambda: add_num(25, 30)
print(f()) # prints 55

# the lambda definition is equivilent to
def f():
    return add_num(25, 30)

It is also possible to modify the original function like you show in the question, but in most cases this would be considered bad style. If you really want to, you can do so by adding the parameters as the .func_defaults attribute of the function object (called .__defaults__ in older versions of Python; documentation).

add_num.func_defaults = (1, 2)
print(add_num()) # prints 3


def gen_add(x, y):
  def add():
    return x + y
  return add

fn =gen_add(2,4)
print fn
print fn()

fn1 = gen_add(5,4)
print fn1()

prints:

<function add at 0x1004d4398>
6
9


import functools
x = functools.partial(add_num, 5, 2)
print x()


import functools
addnum = lambda x,y:x+y
print addnum(5,2) #print 7
z = functools.partial(addnum,5,2)
print z() #print 7
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜