首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >将Python argparse.Namespace()作为字典对待的正确方式是什么?

将Python argparse.Namespace()作为字典对待的正确方式是什么?
EN

Stack Overflow用户
提问于 2013-06-02 07:33:57
回答 4查看 184.2K关注 0票数 303

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

代码语言:javascript
复制
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__看起来像是实现的约定,但不像__getattribute____setattr____contains__那样适用于接口。

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16878315

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档