如何使用python从字符串定义函数

zjm*_*126 8 python string function

这是我的代码:

a = \
'''def fun():\n
    print 'bbb'
'''
eval(a)

fun()
Run Code Online (Sandbox Code Playgroud)

但它显示错误:

Traceback (most recent call last):
  File "c.py", line 8, in <module>
    eval(a)
  File "<string>", line 1
    def fun():
      ^
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)

那我该怎么办

谢谢

Mat*_*nen 13

eval()带字符串参数仅适用于表达式.如果要执行语句,请使用exec:

exec """def fun():
  print 'bbb'
"""
Run Code Online (Sandbox Code Playgroud)

但在此之前,请考虑一下您是否真的需要动态代码.到目前为止,大多数事情都可以不用.