简体   繁体   English

Python为后续函数调用设置参数值

[英]Python set parameter value for subsequent function calls

Is there an option in Python to define a parameter values for some functions so that those values are used when the mentioned functions are called? Python 中是否有选项可以为某些函数定义参数值,以便在调用上述函数时使用这些值?

Something like this in TF Slim: https://www.tensorflow.org/api_docs/python/tf/contrib/framework/arg_scope在 TF Slim 中是这样的: https : //www.tensorflow.org/api_docs/python/tf/contrib/framework/arg_scope

Example:例子:

set_default_params(functions=[func_1, func_2], params=[param_1=value_1, param_2=value_2, param_3=value_3])

After this, when I call func_1() which has default params param_1=0 and param_2=None , it would actually get param_1=value_1 and param_2=value_2 without the need to set it manually when calling func_1() .在此之后,当我调用具有默认参数param_1=0param_2=None func_1() ,它实际上会得到param_1=value_1param_2=value_2而无需在调用func_1()时手动设置它。

You can use functools.partial to set default parameters.您可以使用functools.partial来设置默认参数。 This partially applies parameters to a given function.这部分地将参数应用于给定的函数。

import functools

def func(param, *args, **kwargs):
    print('param:', param)
    print('args:', *args)
    print('kwargs:', kwargs)

g = functools.partial(func, 21)      # sets default value for param to 21
g('arg1', 'arg2', 'arg3', kw='kwarg1')

Output:输出:

param: 21
args: arg1 arg2 arg3
kwargs: {'kw': 'kwarg1'}

Note that a new function is returned from functools.partial and the default parameters aren't set in-place as your set_default_params call implies.请注意,从functools.partial返回了一个新函数,并且默认参数没有像您的set_default_params调用所暗示的那样就地设置。

If you want to be able to set params in the future, you can use some kind of decorators to do it.如果您希望将来能够设置参数,您可以使用某种装饰器来完成。

def kind_of_decorator(func, params):
    def wrapper(*args, **kwargs):
        return func(*args, **dict(kwargs, **params))
    return wrapper

def foo(x, y=2):
    return x + y

print(foo(1, 5)) # prints 6
print(foo(3))    # prints 5

new_foo = kind_of_decorator(foo, {'y': 0})

print(new_foo(1, y=5))  # prints 6
print(new_foo(3))       # prints 3
#print(new_foo(1, 5))   # an error "TypeError: bar() got multiple values for argument 'y'" be careful there. Now only kwargs are allowed for `y`

Maybe not quite in that form, but if you define a function with def function(arg={}) , then the arg argument's default value will persist between calls rather than being set to a new object.也许不是那种形式,但如果你用def function(arg={})定义一个函数,那么arg参数的默认值将在调用之间保持不变,而不是被设置为一个新对象。 That means you could use:这意味着您可以使用:

def function1(arg1, arg2=None, arg3=None, args={"arg2": 42, "arg3": 43}):
    if arg2 is not None:
        args["arg2"] = arg2
    if arg3 is not None:
        args["arg3"] = arg3
    arg2, arg3 = args["arg2"], args["arg3"]
    print(arg1, arg2, arg3)

function1(1)  # prints 1 42 43; using default values for arg2 and arg3
function1(1, 2) # prints 1 2 43; replace arg2 but keep arg3
function1(1, arg3=3) # prints 1 2 3; replace arg3 but keep arg2 from previous call
function1(0)  # prints 0 2 3; both arg2 and arg3 persist from previous calls.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Python:缓存一个本地 function 变量以供后续调用 - Python: cache a local function variable for subsequent calls 如何模拟 python 中的后续 function 调用? - How to mock subsequent function calls in python? Python:重新初始化函数的默认值,以供随后对该函数的调用 - Python: re-initialize a function's default value for subsequent calls to the function Python代码未执行主函数和后续函数调用 - Python code not executing main function and subsequent function calls 如何模拟具有特定参数的函数并返回在Python单元测试中调用另一个函数的值? - How to mock a function with specific parameter and return value that calls another function in python unit test? 嵌套函数调用和缺少输入参数,python - Nested function calls and missing input parameter, python 在 python 中写入清洁器 function,参数可以是集合或值 - Writing a cleaner function in python, a parameter to be either a set or a value Python:参数类型为function时如何设置默认值? - Python: How to set the default value when the parameter type is function? Python循环调用同一个function,并以最后一次调用的返回值作为本次调用的参数 - Python calls the same function in a loop, and uses the return value of the last call as the parameter of this call 在评估等于2个函数调用的结果时,寻找一种方法(理想情况下在Python中)以获取第二个参数值 - Looking for a way (ideally in Python) to obtain a second parameter value when evaluating the result from equating 2 function calls
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM