2024-05-16 09:57:06 发布
网友
我有一个接受通配符关键字参数的函数:
def func(**kargs): doA doB
我怎么给它寄字典?
只要用func(**some_dict)来调用它。
func(**some_dict)
这在section 4.7.4 of python tutorial上有记录。
请注意,相同的dict不是传递到函数中的。将创建一个新副本,因此some_dict is not kwargs。
dict
some_dict is not kwargs
你的问题并不是百分之百的清楚,但是如果你想通过dict传递一个kwargs,你只需要将这个dict作为另一个dict的一部分,就像这样:
kwargs
my_dict = {} #the dict you want to pass to func kwargs = {'my_dict': my_dict } #the keyword argument container func(**kwargs) #calling the function
然后可以在函数中捕捉my_dict:
my_dict
def func(**kwargs): my_dict = kwargs.get('my_dict')
或者。。。
def func(my_dict, **kwargs): #reference my_dict directly from here my_dict['new_key'] = 1234
当我将相同的选项集传递给不同的函数时,我经常使用后者,但有些函数只使用某些选项(我希望这有意义…)。 但这件事当然有上百万条路要走。如果你详细说明一下你的问题,我们很可能会帮你更好。
只要用
func(**some_dict)
来调用它。这在section 4.7.4 of python tutorial上有记录。
请注意,相同的
dict
不是传递到函数中的。将创建一个新副本,因此some_dict is not kwargs
。你的问题并不是百分之百的清楚,但是如果你想通过
dict
传递一个kwargs
,你只需要将这个dict作为另一个dict的一部分,就像这样:然后可以在函数中捕捉
my_dict
:或者。。。
当我将相同的选项集传递给不同的函数时,我经常使用后者,但有些函数只使用某些选项(我希望这有意义…)。 但这件事当然有上百万条路要走。如果你详细说明一下你的问题,我们很可能会帮你更好。
相关问题 更多 >
编程相关推荐