如何在python中使用保留关键字作为变量名?

How to use reserved keyword as the name of variable in python?

我想使用保留关键字"from"作为变量名。

我在我的参数解析器中有它:

parser.add_argument("--from")
args = parser.parse_args()
print(args.from)

但这不起作用,因为 "from" 已保留。拥有这个变量名很重要,我不想要像 "from_".

这样的答案

有什么办法吗?

您可以使用getattr()访问属性:

print(getattr(args, 'from'))

但是,在 argparse 中,您可以使用命令行选项 --from 而无需 属性 from 通过使用 dest option 指定要使用的替代名称:

parser.add_argument('--from', dest='from_')

# ...
args = parser.parse_args()
print(args.from_)