简体   繁体   English

如何在外部函数中定义内部函数的参数名称?

[英]How can I define the argument name of an inner function in an outer function?

I have a function f_1 with different default input arguments, eg arg_1 and arg_2. 我有一个函数f_1,具有不同的默认输入参数,例如arg_1和arg_2。 Now I want to call f_1 with another function f_2 and change one of the default arguments, let us say arg_1. 现在,我想用另一个函数f_2调用f_1并更改默认参数之一,让我们说arg_1。 How can I tell f_2 that I want to change arg_1 in f_1? 如何告诉f_2我想在f_1中更改arg_1?

def f_1(arg_1 = x, arg_2 = y):
    some computations
    return result

def f_2(value_for_arg_f_1, name_arg_f_1):
    do some stuff
    out_f_1 = f_1(name_arg_f_1 = value_for_arg_f_1)
    do some more stuff
    return result_f_2
end_result = f_2(z, arg_2)

So looking in the example code - what do I have to write for name_arg_f_1 in f_2, such that (in the computation of end_result) out_f_1 = f_1(arg_2=z)? 因此,请看示例代码-我必须为f_2中的name_arg_f_1写什么,以便(在计算end_result时)out_f_1 = f_1(arg_2 = z)?

You can use lambda functions, for example, 您可以使用lambda函数,例如,

def adder(x=2, y=3):
    return x+y

adder()
# 5

adderEight = lambda y: adder(8, y)
adderEight(10)
# 18

You could use the example from [Python 3.Docs]: Glossary - argument : 您可以使用[Python 3.Docs]中的示例:词汇表- 参数

 complex(real=3, imag=5) complex(**{'real': 3, 'imag': 5}) 

It relies on [Python]: PEP 448 - Additional Unpacking Generalizations . 它依赖于[Python]:PEP 448-其他拆包概述

 >>> def f1(arg1=1, arg2=2): ... print(" Argument 1: [{:}], Argument 2: [{:}]".format(arg1, arg2)) ... >>> >>> f1() Argument 1: [1], Argument 2: [2] >>> >>> def f2(f1_arg_val, f1_arg_name): ... f1(**{f1_arg_name: f1_arg_val}) ... >>> >>> f2("value for argument 2", "arg2") Argument 1: [1], Argument 2: [value for argument 2] 

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

相关问题 当外部函数具有同名的关键字参数时,将关键字参数传递给内部函数 - passing keyword argument to inner function when outer function has keyword argument with the same name 将外部 function 的参数作为内部 function 的参数传递给 python? - passing argument of outer function as argument for inner function in python? 根据传递给外部函数的参数调用内部函数 - Call inner function based on the argument passed to outer function 在python中将相同的参数从外部函数传递给内部函数 - passing same argument from outer function to inner function in python 从python中的内部函数对象获取外部函数的名称 - Get name of outer function from inner function object in python 如何在python中计算外部函数? - How can I calculate an outer function in python? 如何覆盖外部的内部方法函数 - how to override inner method function in outer 在Python中,如何定义一个函数包装器来验证具有特定名称的参数? - In Python, how to define a function wrapper which validates an argument with a certain name? 最内层function如何访问Python中最外层function中的非局部变量? - How can the most inner function access the non-local variable in the most outer function in Python? 我们可以使用外部函数在python中访问其外部函数范围之外的内部函数吗? - Can we access inner function outside its scope of outer function in python using outer function?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM