如何在Python中使用保留关键字作为变量名?
问题描述:
我想使用保留关键字"from"作为变量的名称.
I want to use reserved keyword "from" as the name of variable.
我将其保存在参数解析器中
I have it in my arguments parser:
parser.add_argument("--from")
args = parser.parse_args()
print(args.from)
但是这不起作用,因为保留了"from".具有此变量名很重要,我不希望像"from_"这样的答案.
but this isn't working because "from" is reserved. It is important to have this variable name, I don't want answers like "from_".
有什么选择吗?
答
您可以使用getattr()
访问该属性:
You can use getattr()
to access the attribute:
print(getattr(args, 'from'))
但是,在argparse
中,可以使用 dest
选项指定要使用的备用名称:
However, in argparse
you can have the command-line option --from
without having to have the attribute from
by using the dest
option to specify an alternative name to use:
parser.add_argument('--from', dest='from_')
# ...
args = parser.parse_args()
print(args.from_)