Jas*_*n S 201 python dictionary duck-typing
如果我想使用一个需要字典或类似映射的对象的方法(参见collections.Mapping)来使用argparse.ArgumentParser()
作为Namespace
对象的结果,那么正确的方法是什么?
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']
Run Code Online (Sandbox Code Playgroud)
"伸手"进入某个物体并使用其__dict__
财产是否合适?
我认为答案是否定的:__dict__
闻起来像执行公约,而不是一个接口,方式__getattribute__
或__setattr__
或__contains__
似乎是.
Ray*_*ger 320
您可以使用vars()访问命名空间的字典:
>>> import argparse
>>> args = argparse.Namespace()
>>> args.foo = 1
>>> args.bar = [1,2,3]
>>> d = vars(args)
>>> d
{'foo': 1, 'bar': [1, 2, 3]}
Run Code Online (Sandbox Code Playgroud)
如果您愿意,可以直接修改字典:
>>> d['baz'] = 'store me'
>>> args.baz
'store me'
Run Code Online (Sandbox Code Playgroud)
是的,可以访问__dict__属性.它是一种定义明确,经过测试和保证的行为.
Eug*_*ash 52
如果您希望使用类似于dict的属性视图,则可以使用标准的Python习惯用法
vars()
:Run Code Online (Sandbox Code Playgroud)>>> parser = argparse.ArgumentParser() >>> parser.add_argument('--foo') >>> args = parser.parse_args(['--foo', 'BAR']) >>> vars(args) {'foo': 'BAR'}
- Python标准库,16.4.4.6.Namespace对象
归档时间: |
|
查看次数: |
107038 次 |
最近记录: |