Skip to main content
 首页 » 编程设计

python之python中有 'execute'语句吗

2025年05月04日11jiqing9006

在 python 中是否有像“执行”语句这样的东西,我可以像下面那样使用它?

statement='print "hello world"' 
 
def loop(statement): 
    for i in range(100): 
        for j in range(100): 
            execute statement 
 
loop(statement) 

请您参考如下方法:

是的,只需传递一个 callable 并使用 statement() 来执行它。

可调用 是函数、lambda 表达式或任何其他实现 __call__ 的对象.

def loop(func): 
    for i in range(100): 
        for j in range(100): 
            func() 
 
def say_hello(): 
    print "hello world" 
loop(say_hello) 

如果你真的想从一个字符串中执行代码(相信我,你不需要!),有 exec :

>>> code = 'print "hello bad code"' 
>>> exec code 
hello bad code