简体   繁体   English

函数参数中的动态变量

[英]Dynamic variable in function argument

Let us say I have a function like this: 让我们说我有一个这样的功能:

def helloWorld(**args):
    for arg in args:
        print(args[arg])

To call this function is easy: 调用此函数很容易:

helloWorld(myMsg = 'hello, world')
helloWorld(anotherMessages = 'no, no this is hard')

But the hard part is that I want to dynamically name the args from variables coming from a list or somewhere else. 但是困难的部分是我想根据来自列表或其他位置的变量来动态命名args。 And I'd want for myMsg and anotherMessages to be passed from a list (for example, the hard part that I am clueless and I need help with is how to take strings into variables to be inputs of a function). 而且我希望从列表中传递myMsg和anotherMessages(例如,我一无所知,我需要帮助的困难部分是如何将字符串带入变量作为函数的输入)。

list_of_variable_names = ['myMsg','anotherMessages']
for name in list_of_variable_names:
    helloWorld(name = 'ooops, this is not easy, how do I pass a variable name that is stored as a string in a list? No idea! help!')

You can create a dict using the variable and then unpack while passing it to the function: 您可以使用变量创建字典,然后在将其传递给函数时解压缩:

list_of_variable_names = ['myMsg','anotherMessages']
for name in list_of_variable_names:
    helloWorld(**{name: '...'})

The ** syntax is a dictionary unpacking. **语法是字典解压缩。 So in your function, args (which is usually kwargs ) is a dictionary. 因此,在您的函数中, args (通常为kwargs )是一个字典。

Therefore, you need to pass an unpacked dictionary to it, which is what is done when f(a=1, b=2) is called. 因此,您需要传递一个解压缩的字典给它,这就是调用f(a=1, b=2)时要做的。

For instance: 例如:

kwargs = {'myMsg': "hello, world", 'anotherMessages': "no, no this is hard"}
helloWorld(**kwargs)

Then, you will get kwargs as a dictionary. 然后,您将获得kwargs作为字典。

def f(**kwargs):
    for k, v in kwargs.items():
        print(k, v)

>>> kwargs = {'a': 1, 'b': 2}
>>> f(**kwargs)
a 1
b 2

If you want to do so, you can call the function once for every name as well, by creating a dictionary on the fly and unpacking it, as Moses suggested . 如果您愿意,也可以按照Moses的建议 ,通过动态创建字典并将其解压缩,为每个名称调用一次函数。

def f(**kwargs):
    print("call to f")
    for k, v in kwargs.items():
        print(k, v)

>>> for k, v in {'a': 1, 'b': 2}:
...     kwargs = {k: v}
...     f(**kwargs)
...
call to f
a 1
call to f
b 2

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

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