我想用python构造一个类,它支持从用户提供的源代码中动态更新方法。在
类Agent
的实例有一个方法go
。在构造实例时,它的.go()
方法什么也不做。例如,如果我们做a=Agent()
,然后a.go()
,我们应该得到NotImplementedError
或类似的东西。然后用户应该能够通过提供源代码来交互式地定义a.go()
。一个简单的源代码示例是
mySourceString="print('I learned how to go!')"
会像这样被注入a
a.update(mySourceString)
进一步调用a.go()
将导致"I learned how to go!"
被打印到屏幕上。在
我已经用下面的代码部分地解决了这个问题:
import types
class Error(Exception):
"""Base class for exceptions in this module."""
pass
class NotImplementedError(Error):
pass
class Agent(object):
def go(self):
raise NotImplementedError()
def update(self,codeString):
#Indent each line of user supplied code
codeString = codeString.replace('\n','\n ')
#Turn code into a function called func
exec "def func(self):\n"+' '+codeString
#Make func a bound method on this instance
self.go = types.MethodType(func, self)
问题
可能有用的SO帖子
(我在Python2.6中工作)
目前没有回答
相关问题 更多 >
编程相关推荐