What is a namespace object?

岁酱吖の 提交于 2019-12-06 18:42:35

问题


import argparse

parser = argparse.ArgumentParser(description='sort given numbers')
parser.add_argument('-s', nargs = '+', type = int)
args = parser.parse_args()
print(args)

On command line when I run the command

python3 file_name.py -s 9 8 76

It prints Namespace(s=[9, 8, 76]).

How can I access the list [9, 8, 76]? What is the namespace object. Where can I learn more about it?


回答1:


  • The documentation for argparse.Namespace can be found here.
  • You can access the s attribute by doing args.s.
  • If you'd like to access this as a dictionary, you can do vars(args), which means you can also do vars(args)['s']



回答2:


It is the result object that argparse returns; the items named are attributes:

print(args.s)

This is a very simple object, deliberately so. Your parsed arguments are attributes on this object (with the name determined by the long option, or if set, the dest argument).




回答3:


you can access as args.s , NameSpace class is deliberately simple, just an object subclass with a readable string representation. If you prefer to have dict-like view of the attributes, you can use the standard Python idiom, vars(). Source



来源:https://stackoverflow.com/questions/20828277/what-is-a-namespace-object

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!