gpt4 book ai didi

python - 如何在 python 代码中利用 locals()?

转载 作者:太空狗 更新时间:2023-10-29 20:20:44 25 4
gpt4 key购买 nike

我在阅读 Code Like a Pythonista: Idiomatic Python 时偶然发现了以下警告大卫·古杰 (David Goodger)。

Excerpt from the article ...

print('Hello %(name)s, you have %(messages)i messages' % locals())

This is very powerful. With this, you can do all the string formatting you want without having to worry about matching the interpolation values to the template.

But power can be dangerous. "With great power comes great responsibility." If you use the locals() from with an externally-supplied template string, you expose your entire local namespace to the caller. This is just something to keep in mind.

我正在尝试了解使用 locals() 可能很危险的特定场景。任何有关如何利用代码中存在的 locals() 的示例都值得赞赏。谢谢!

最佳答案

示例,简单的代码:

script_name = 'readpw.py'
...
entered_pw = raw_input()
if entered_pw != real_pw:
print "%(script_name)s: The password you entered: "+entered_pw+" is incorrect."%locals()

考虑 entered_pw 为 %(real_pw)s

的情况

关于python - 如何在 python 代码中利用 locals()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5585648/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com