[英]Define a python function based on previously defined function specifying argument
I have one defined function and I would like to define another one which is exactly the same as the first, but specifying one parameter. 我有一个已定义的函数,我想定义另一个与第一个完全相同的函数,但指定一个参数。
One possible way of doing that is 一种可行的方式是
def my_function(arg1, arg2):
print(arg1, arg2)
def my_function_foo(arg1):
return(my_function(arg1, 'bar'))
>>> my_function_foo('foo')
foo bar
But I suppose there is a cleaner way, closer to: 但我想有一种更清洁的方法,可以更接近:
my_function_foo = my_function(arg2 = 'foo')
Use functools.partial
: 使用functools.partial
:
>>> from functools import partial
>>> my_function_foo = partial(my_function, arg2='bar')
>>> my_function_foo('foo')
foo bar
Note that my_function_foo
is not technically a function
, but an instance of partial
. 注意my_function_foo
从技术上讲不是function
,而是partial
的实例。 Calling the instance calls the underlying function using the previously given and current arguments merged in the expected way. 调用实例将使用以预期方式合并的先前给定和当前参数来调用基础函数。
You can create a decorator that will pass the parameter for you. 您可以创建一个装饰器,该装饰器将为您传递参数。
from functools import wraps
def give_param(param='bar'):
def inner_function(func):
@wraps(func)
def wrapper(*args, **kwargs):
return func(*args, arg2=param)
return wrapper
return inner_function
@give_param('bar')
def my_function(arg1,arg2):
# do some stuff
print(arg1,arg2)
So if you want arg2 = 3, 因此,如果您希望arg2 = 3,
@give_param(3)
def my_function(arg1,arg2):
# do some stuff
print(arg1,arg2)
You might solve your problem with an inner function as follows: 您可以使用以下内部函数解决问题:
def my_function(arg1, arg2='bar'):
def my_function_foo(arg1):
print(arg1, arg2)
return my_function_foo(arg1)
my_function(arg1 = 'foo')
You could use the multiple dispatch library to do a method override like in C: 您可以使用多重调度库来像C中那样进行方法覆盖:
from multipledispatch import dispatch
@dispatch(object, object)
def my_function(arg1, arg2):
print(arg1, arg2)
@dispatch(object)
def my_function(arg1):
return(my_function(arg1, 'bar'))
my_function('foo')
my_function('foo', 'foo')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.