是否可以做类似的事情
c = MyObj()
c.eval("func1(42)+func2(24)")
在 Python..ie 中有 func1() 和 func2() 在对象“c”的范围内进行评估(如果它们是该类定义中的成员函数)?我无法进行简单的解析,因为对于我的应用程序,eval 字符串可能会变得任意复杂。我想用 ast 模块做一些魔术可能会奏效,但由于关于 ast 的文献很脏,我不确定在哪里看:
import ast
class MyTransformer(ast.NodeTransformer):
def visit_Name(self, node):
# do a generic_visit so that child nodes are processed
ast.NodeVisitor.generic_visit(self, node)
return ast.copy_location(
# do something magical with names that are functions, so that they become
# method calls to a Formula object
newnode,
node
)
class Formula(object):
def LEFT(self, s, n):
return s[:n]
def RIGHT(self, s, n):
return s[0-n:]
def CONCAT(self, *args, **kwargs):
return ''.join([arg for arg in args])
def main():
evalString = "CONCAT(LEFT('Hello', 2), RIGHT('World', 3))"
# we want to emulate something like Formula().eval(evalString)
node = ast.parse(evalString, mode='eval')
MyTransformer().visit(node)
ast.fix_missing_locations(node)
print eval(compile(node, '<string>', mode='eval'))