我很想学点有用的东西,因为现在我一直在盲目地摸索。
问题出在Python的ast.NodeTransformer上。我想知道是否可以通过这种方式向现有类添加一个函数,而不会发疯。
以下是我迄今为止的做法。
我尝试过(不成功,你可能已经猜到了)使用ast库的辅助函数ast.fix_missing_locations()和ast.copy_location()来处理这个问题,但在大多数情况下,我最终只能猜测或面对AddFunc类中的元组引发的AttributeError。有人有什么想法,如何解决这个问题吗?
以下是我迄今为止的做法。
import ast, inspect, cla # cla is a name of class to which we want to add a new function
klass = inspect.getsource(cla)
tree = ast.parse(klass)
st = '''def function(): return 1'''
Foo = ast.parse(st)
class AddFunc(ast.NodeTransformer):
def visit_ClassDef(self, node):
return node, node.body + Foo.body
self.generic_visit(node)
inst = AddFunc()
stuff = i.visit(tree)
# now the trouble begins, a compiling..
co = compile(stuff, filename='<ast>', mode='exec')
# i get TypeError: required "lineno" missing from stmt
我尝试过(不成功,你可能已经猜到了)使用ast库的辅助函数ast.fix_missing_locations()和ast.copy_location()来处理这个问题,但在大多数情况下,我最终只能猜测或面对AddFunc类中的元组引发的AttributeError。有人有什么想法,如何解决这个问题吗?