如何使用python从一个字符串定义一个函数 [英] how to define a function from a string using python

查看:231
本文介绍了如何使用python从一个字符串定义一个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

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

fun()

但它显示错误:

 追踪(最近的最后一次调用) :
在< module>中,第8行的文件c.py
eval(a)
文件< string>,第1行
def fun():
^
语法错误:语法无效

所以我能做什么,

谢谢

解决方案

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

  exec def fun():
print'bbb'

但在你这样做之前,要考虑你是否真的需要动态代码。到目前为止,大多数情况下都可以不用。


this is my code :

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

fun()

but it shows error :

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

so what can i do ,

thanks

解决方案

eval() with string a string argument is only for expressions. If you want to execute statements, use exec:

exec """def fun():
  print 'bbb'
"""

But before you do that, think about whether you really need dynamic code or not. By far most things can be done without.

这篇关于如何使用python从一个字符串定义一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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