将dict传递给构造函数? [英] Passing dict to constructor?

查看:89
本文介绍了将dict传递给构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将字典传递给对象的构造函数以用作kwarg.

I'd like to pass a dict to an object's constructor for use as kwargs.

很明显:

foo = SomeClass(mydict)

只传递一个参数,而不是字典的内容. las:

Simply passes a single argument, rather than the dict's contents. Alas:

foo = SomeClass(kwargs=mydict)

似乎更明智的选择也不起作用.我想念什么?

Which seems more sensible doesn't work either. What am I missing?

推荐答案

使用情况:

foo = SomeClass(**mydict)

这将解压缩dict值并将其传递给函数.

this will unpack the dict value and pass them to the function.

例如:

mydict = {'a': 1, 'b': 2}

SomeClass(**mydict) # Equivalent to : SomeClass(a=1, b=2)

这篇关于将dict传递给构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆