存储函数时如何传递预定义的参数 [英] How to pass predefined arguments when storing a function

查看:54
本文介绍了存储函数时如何传递预定义的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以存储带有预定义参数的函数以供另一个函数调用?

Is it possible to store a function with predefined arguments to be called by another function?

例如:

def function(num):
    print num

trigger=function #store function(1)
trigger()        #prints 1

trigger=function #store function(2)
trigger()        #prints 2

trigger调用存储的任何内容而不传递任何参数.我可以更改触发器,但是这需要我重写调用触发器的函数,所以我想知道在将函数存储在变量中时是否存在一种将函数与参数一起存储的方法.

trigger calls whatever is stored without passing any arguments. I can change trigger but that would require me to rewrite the function that calls the trigger, so I'm wondering if there is a way to store functions along with arguments when storing a function in a variable.

推荐答案

您正在寻找 functools.partial :

You're looking for functools.partial:

>>> import functools
>>> def foo(number):
...     print number
... 
>>> bar = functools.partial(foo, 1)
>>> bar()
1

这篇关于存储函数时如何传递预定义的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆