在函数内部运行exec [英] Running exec inside function

查看:106
本文介绍了在函数内部运行exec的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在函数内部使用python exec关键字?

解决方案

这会损害你函数的性能,以及它的可维护性,但是如果你真的想让你自己的代码变得更糟,那么Python会给你足够的绳索来拍摄你自己的脚(; - ):

 >>> def horror():
... execx = 23
... return x
...
>>>打印恐怖()
23

当然,不那么可怕的是 exec 在特定字典中:

 >>> def better():
... d = {}
... execx = 23in d
... return d ['x']
。 ..
>>>打印更好()
23

这至少避免了命名空间 - 第一种方法的污染。


How can you use the python exec keyword inside functions?

解决方案

It's going to damage your function's performance, as well as its maintainability, but if you really want to make your own code so much worse, Python gives you "enough rope to shoot yourself in the foot" (;-):

>>> def horror():
...   exec "x=23"
...   return x
... 
>>> print horror()
23

A tad less horrible, of course, would be to exec in a specific dict:

>>> def better():
...   d = {}
...   exec "x=23" in d
...   return d['x']
... 
>>> print better()
23

This at least avoids the namespace-pollution of the first approach.

这篇关于在函数内部运行exec的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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