我试图动态地定义一个类,然后实例化它。为此,我要做的是,将类定义作为字符串,并在运行时将其提供给eval函数来定义它。你知道吗
f="""class f:
def pr(self):
print "asdfg"
"""
>>> eval(f)
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
eval(f)
File "<string>", line 1
class f:
^
SyntaxError: invalid syntax
我之所以这样做是因为有很多类可以使用,但很少是他们都需要在一起。另外,我允许用户向应用程序添加新类。你知道吗
提前谢谢。你知道吗
编辑------------------
这是python2.5的输出
data = """class f:
def pr(self):
print "asdfg"
"""
>>> exec(data)
Traceback (most recent call last):
File "<pyshell#14>", line 1, in <module>
exec(data)
File "<string>", line 4
^
SyntaxError: invalid syntax
#What i think the problem is "\n"
>>> data
'class f:\n def pr(self):\n print "asdfg"\n '
我不确定,但那就是错误所在。你知道吗
使用python2.5的原因是,scapy是程序的一部分,它只支持python2.5。你知道吗
使用^{} ,而不是
eval
。exec
将执行任意代码,而eval
将只计算表达式(例如eval('2+3') == 5
)。你知道吗不过,也许有更好的方法来实现你想做的事情。让程序的用户创建新类似乎是次优的设计选择。你知道吗
相关问题 更多 >
编程相关推荐