什么是动态创建Python对象实例的最佳方法是将Python类保存为字符串?
作为背景,我在Google Application Engine环境中工作,我希望能够从类的字符串版本动态加载类.
problem = “1,2,3,4,5”
solvertext1 = “””class solver:
def solve(self, problemstring):
return len(problemstring) “””
solvertext2 = “””class solver:
def solve(self, problemstring):
return problemstring[0] “””
solver = #The solution code here (solvertext1)
answer = solver.solve(problem) #answer should equal 9
solver = #The solution code here (solvertext2)
answer = solver.solve(problem) # answer should equal 1
Run Code Online (Sandbox Code Playgroud) python ×1