Python 什么是命名空间对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20828277/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is a namespace object?
提问by Shashank Garg
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
python3 file_name.py -s 9 8 76
It prints
Namespace(s=[9, 8, 76]).
它打印
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?
如何访问列表 [9, 8, 76]?什么是命名空间对象。我在哪里可以了解更多信息?
采纳答案by Bill Lynch
- The documentation for
argparse.Namespacecan be found here. - You can access the
sattribute by doingargs.s. - If you'd like to access this as a dictionary, you can do
vars(args), which means you can also dovars(args)['s']
argparse.Namespace可以在此处找到的文档。- 您可以
s通过执行访问该属性args.s。 - 如果你想以字典的形式访问它,你可以做
vars(args),这意味着你也可以做vars(args)['s']
回答by Martijn Pieters
It is the result object that argparsereturns; the items named are attributes:
返回的是结果对象argparse;命名的项目是属性:
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 destargument).
这是一个非常简单的对象,故意如此。您解析的参数是此对象的属性(名称由 long 选项确定,如果设置,则为dest参数)。
回答by Veaceslav Mindru
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
您可以访问 as args.s,NameSpace 类故意简单,只是具有可读字符串表示形式的对象子类。如果您更喜欢使用类似 dict 的属性视图,您可以使用标准的 Python 习惯用法 vars()。来源

