使用字符串变量** kwargs作为命名参数 [英] Use string variable **kwargs as named argument
问题描述
我试图找出一种方法循环通过一个json配置文件,并使用键名称作为参数名称的方法使用** kwargs。我创建了一个json配置文件,并使用键名称作为方法。我只是将set_附加到键名称以调用正确的方法。我将json转换为字典循环通过任何默认值。我想通过字符串变量传递参数名称到** kwargs。我尝试传递一个字典,但似乎不喜欢这样。
I am trying to figure out a way to loop through a json config file and use a key name as the argument name to a method that uses **kwargs. I have created a json config file and used key names as methods. I just append "set_" to the key name to call the correct method. I convert the json to a dictionary to loop through any of the defaults. I want to pass argument names to **kwargs by a string variable. I tried to pass a dictionary but it doesn't seem to like that.
user_defaults = config['default_users'][user]
for option_name, option_value in user_defaults.iteritems():
method = "set_" + option_name
callable_method = getattr(self, method)
callable_method(user = user, option_name = user_defaults[option_name])
调用上述callable_method时, kwarg的名称。我想传递它,所以当shell= option_name它作为参数名称的字符串名称传递。下面是一个例子。这样我可以循环通过配置中的任何键,不担心我在寻找什么我写的任何方法来完成的东西。
Calling the callable_method above passes "option_name" as the actual name of the kwarg. I want to pass it so that when "shell" = option_name that it gets passed as the string name for the argument name. An example is below. That way I can loop through any keys in the config and not worry about what I'm looking for in any method I write to accomplish something.
def set_shell(self, **kwargs):
user = kwargs['user']
shell = kwargs['shell']
## Do things now with stuff
任何帮助是赞赏我是新的python,仍然学习如何做的事情的pythonic方式。
Any help is appreciated I am new to python and still learning how to do things the pythonic way.
推荐答案
正确地你要求的,你可以使用 **
语法在主叫端传递一个被转换成kwargs的dict。
If I understand correctly what you're asking, you can just use the **
syntax on the calling side to pass a dict that is converted into kwargs.
callable_method(user=user, **{option_name: user_defaults[option_name]})
这篇关于使用字符串变量** kwargs作为命名参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!