python - 将 Python argparse.Namespace() 视为字典的正确方法是什

如果我想使用 argparse.ArgumentParser() 的结果,它是一个 Namespace 对象,其方法需要一个字典或类似映射的对象(请参阅 collections.Mapping ),正确的做法是什么?

C:\>python
Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>> import argparse
>>> args = argparse.Namespace()
>>> args.foo = 1
>>> args.bar = [1,2,3]
>>> args.baz = 'yippee'
>>> args['baz']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'Namespace' object has no attribute '__getitem__'
>>> dir(args)
['__class__', '__contains__', '__delattr__', '__dict__', '__doc__', '__eq__', '_
_format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__',
'__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__
', '__str__', '__subclasshook__', '__weakref__', '_get_args', '_get_kwargs', 'ba
r', 'baz', 'foo']

“进入”一个对象并使用它的 __dict__ 属性是否合适?

我认为答案是否定的:__dict__ 闻起来像一个实现约定,但不是一个接口(interface),就像 __getattribute____setattr____contains__ 似乎是。

最佳答案

您可以使用 vars() 访问命名空间的字典:

>>> import argparse
>>> args = argparse.Namespace()
>>> args.foo = 1
>>> args.bar = [1,2,3]
>>> d = vars(args)
>>> d
{'foo': 1, 'bar': [1, 2, 3]}

如果您愿意,可以直接修改字典:

>>> d['baz'] = 'store me'
>>> args.baz
'store me'

是的,可以访问 __dict__ 属性。这是一种定义明确、经过测试且有保证的行为。

关于python - 将 Python argparse.Namespace() 视为字典的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16878315/

相关文章:

linux - Bash中的 'eval'命令及其典型用途

python - 从标准输入读取密码

python - 如果对象存在,我如何获取它,或者如果它在 Django 中不存在,我如何获取它?

linux - 在 Linux 上的目录中获取最新文件

python - 用 Python 构建一个最小的插件架构

linux - 单个主机上的多个 glibc 库

python - 使用 Python 进行网页抓取

mysql - 错误 1045 (28000) : Access denied for user '

linux - "/usr/bin/ld: cannot find -lz"

python - scikit-learn 中跨多个列的标签编码