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

本文讨论了如何在Python中将argparse.Namespace对象转换为字典或映射对象,以便于使用需要字典参数的方法。通过示例展示了直接访问Namespace的__dict__属性可能不是最佳选择,因为它涉及实现细节而非标准接口。
摘要由CSDN通过智能技术生成

如果我想使用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 "", line 1, in

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__那样。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值