python指针参数,Python,如何传递参数到函数指针参数?

I only just started learning Python and found out that I can pass a function as the parameter of another function. Now if I call foo(bar()) it will not pass as a function pointer but the return value of the used function. Calling foo(bar) will pass the function, but this way I am not able to pass any additional arguments. What if I want to pass a function pointer that calls bar(42)?

I want the ability to repeat a function regardless of what arguments I have passed to it.

def repeat(function, times):

for calls in range(times):

function()

def foo(s):

print s

repeat(foo("test"), 4)

In this case the function foo("test") is supposed to be called 4 times in a row.

Is there a way to accomplish this without having to pass "test" to repeat instead of foo?

解决方案

You can either use a lambda:

repeat(lambda: bar(42))

Or functools.partial:

from functools import partial

repeat(partial(bar, 42))

Or pass the arguments separately:

def repeat(times, f, *args):

for _ in range(times):

f(*args)

This final style is quite common in the standard library and major Python tools. *args denotes a variable number of arguments, so you can use this function as

repeat(4, foo, "test")

or

def inquisition(weapon1, weapon2, weapon3):

print("Our weapons are {}, {} and {}".format(weapon1, weapon2, weapon3))

repeat(10, inquisition, "surprise", "fear", "ruthless efficiency")

Note that I put the number of repetitions up front for convenience. It can't be the last argument if you want to use the *args construct.

(For completeness, you could add keyword arguments as well with **kwargs.)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值