简体   繁体   English

python-调用具有指定变量名称的函数,该函数将值分配给该变量

[英]python - Call a function with a specified variable name assigning value to that variable

I want to be able to pass in the name of variable to a function, and have that function call another function that calls the first function with a particular value assigned to the variable name. 我希望能够将变量名传递给一个函数,并让该函数调用另一个函数,该函数调用为第一个函数分配了特定值的变量名称。 For example: 例如:

# function with argument 'arg2'
def foo(arg1=None, arg2=None, arg3=None):
    print arg2

# function that calls foo with a value assigned to designated variable
def bar(var, value):
    foo(var=value)

So that when I call 这样我打电话时

> foo(arg2, 10)

I get the output 我得到了输出

Output: 10

How is this done? 怎么做?

You can't do that, because it makes no sense; 您不能这样做,因为这没有任何意义。 the name arg2 would always refer to whatever the value of that variable is. 名称arg2将始终引用该变量的值。

You can however pass the string "arg2" , and use kwargs to call the function: 但是,您可以传递字符串 "arg2" ,并使用kwargs调用该函数:

def bar(var, value):
    foo(**{var: value})

although you would be better off doing this directly and removing the need for bar altogether. 尽管您最好直接执行此操作,并完全消除对bar的需求。

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

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