如何从字典初始化SimpleNamespace [英] How to initialize a SimpleNamespace from a dict

查看:872
本文介绍了如何从字典初始化SimpleNamespace的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我敢肯定这很简单,但是我找不到答案。

I'm sure this must be simple, but I could not find the answer.

我有一个像这样的字典:

I have a dictionary like:

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

我想通过点表示法来访问它,例如: da

I'd like to access that via dot notation, like: d.a

SimpleNamespace 是为此目的而设计的,但是我不能仅仅将字典传递给SimpleNamespace构造函数。
我收到错误: TypeError:预期没有位置参数

如何从中初始化SimpleNamespace

How do I initialize the SimpleNamespace from a dictionary?

推荐答案

使用 ** kwargs 调用语法将字典分解成单独的参数:

Pass in the dictionary using the **kwargs call syntax to unpack your dictionary into separate arguments:

SimpleNamespace(**d)

这会将 d 中的每个键值对应用为单独的关键字参数。

This applies each key-value pair in d as a separate keyword argument.

相反,密切相关的类定义__init __ 方法中的 ** kwargs 参数定义 Python文档中显示的 https://docs.python.org/3/library/types.html#types.SimpleNamespace rel = noreferrer> 将传递给该类的所有关键字参数捕获到一个字典中

Conversely, the closely releated **kwargs parameter definition in the __init__ method of the class definition shown in the Python documentation captures all keyword arguments passed to the class into a single dictionary again.

演示:

>>> from types import SimpleNamespace
>>> d = {'a': 1, 'b':2}
>>> sn = SimpleNamespace(**d)
>>> sn
namespace(a=1, b=2)
>>> sn.a
1

这篇关于如何从字典初始化SimpleNamespace的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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