什么是动态创建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)
唉,exec是你唯一的选择,但至少要做好避免灾难的方法:传递一个明确的字典(in当然还有一个条款)!例如:
>>> class X(object): pass
...
>>> x=X()
>>> exec 'a=23' in vars(x)
>>> x.a
23
Run Code Online (Sandbox Code Playgroud)
通过这种方式,您知道exec不会污染一般命名空间,并且正在定义的任何类都将作为属性提供x.几乎可以exec忍受......! - )