如何在Python中使用保留关键字作为变量名? [英] How to use reserved keyword as the name of variable in python?

查看:185
本文介绍了如何在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_)

这篇关于如何在Python中使用保留关键字作为变量名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆