Ale*_*lli 14
它会破坏你的功能性能以及它的可维护性,但如果你真的想让你自己的代码变得更糟,那么Python会给你"足够的绳索来射击你自己"(;-):
>>> def horror():
... exec "x=23"
... return x
...
>>> print horror()
23
Run Code Online (Sandbox Code Playgroud)
当然,一个不那么可怕的事情将是exec在一个特定的字典中:
>>> def better():
... d = {}
... exec "x=23" in d
... return d['x']
...
>>> print better()
23
Run Code Online (Sandbox Code Playgroud)
这至少避免了第一种方法的命名空间污染.
Alex 的答案在 Python 3 中的工作方式略有不同。
由于 exec() 是 Python 3 中的函数,因此请使用以下模式 -
def better():
d = {}
exec("x=23", d)
return d['x']
print better()
23
Run Code Online (Sandbox Code Playgroud)
有关更多详细信息,请参阅此问题 - Behaviour of exec function in Python 2 and Python 3
| 归档时间: |
|
| 查看次数: |
3928 次 |
| 最近记录: |