简体   繁体   English

将函数参数名称传递给Python中的另一个函数

[英]Passing function parameter name to another function in Python

Given a simple function: 给出一个简单的函数:

def A(a = 1, b = 2):
    return a+b

I want to write another function to change the default parameter value, for either a or b . 我想编写另一个函数来更改ab的默认参数值。 And user can specify the parameter to change by setting var = a or var = b . 用户可以通过设置var = avar = b来指定要更改的参数。 For example: 例如:

def B(var = 'a', new_value = 10):
    temp_dict = {var:new_value}
    ans = A(var)
    return ans    

or 要么

def B(var = 'a', new_value = 10):
    ans = A(var = new_value)
    return ans

In function def B() , after setting var = a and var = new_value = 10 , I expect A(var = new_value) to achieve the same effect as A(a = 10) . 在函数def B() ,设置var = avar = new_value = 10 ,我期望A(var = new_value)可以达到与A(a = 10)相同的效果。 Do you know the correct way to write function def B() ? 您知道编写函数def B()的正确方法吗? Thanks. 谢谢。

You are almost there. 你快到了 From your B() function, while making the call to A() , you need to unpack the temp_dict and pass it as an argument to A() . 通过B()函数,在调用A() ,需要解压缩temp_dict并将其作为参数传递给A() See below: 见下文:

>>> def A(a = 1, b = 2):
...     return a+b
...

>>> def B(var = 'a', new_value = 10):
...     temp_dict = {var:new_value}
...     ans = A(**temp_dict)
        #        ^ unpack the dict, and pass it as an argument
...     return ans
...

>>> B()
12

For more details on how this ** works with a dict, please take a look at: 有关此**如何与字典配合使用的更多详细信息,请查看:

I took the liberty of interpreting a bit what the OP said he wanted, ie change the default parameter value, for either a or b . 我可以随意解释OP想要的内容,即更改a或b的默认参数值 So what I did was to return a transformed function A with either the a or b defaults changed via a partial: 所以我要做的是返回转换后的函数A,其中a或b的默认值都通过部分更改:

from functools import partial

def B3(var ="a", new_value=10):
    return partial(A, **{var:new_value})

sample outputs: 样本输出:

(Pdb) f = B3("a",10)
(Pdb) f()
12
(Pdb) f = B3("b",10)
(Pdb) f()
11
(Pdb) f(a=10)
20
(Pdb) f(b=13)
14
(Pdb) f(a=5,b=5)
10

That is different from the 2nd half of the request however, that of having something based on B(var="a",new_value=10) as function signature. 但是,与请求的第二部分不同,该请求具有基于B(var="a",new_value=10)作为函数签名。

The only thing is, it chokes happily if you don't use keyword parameters: 唯一的事情是,如果您不使用关键字参数,它会令人窒息:

(Pdb) f(7,7)
*** TypeError: A() got multiple values for keyword argument 'b'

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM