2009-08-21 27 views
2

什麼是動態創建Python對象實例的最佳方式,當你擁有的是將Python類保存爲字符串?將類實現存儲在字符串中時創建Python對象的最佳方法是什麼?

對於背景,我正在Google應用程序引擎環境中工作,我希望能夠從類的字符串版本動態加載類。

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 
+0

這些都是您使用 – 2009-08-21 07:52:01

+0

爲什麼不直接從文件導入類一些奇怪的報價? – 2009-08-21 10:38:23

回答

9

唉,exec是你唯一的選擇,但至少這樣做的權利,以避免災難:傳遞一個明確的解釋(用當然是in條款)!例如: -

>>> class X(object): pass 
... 
>>> x=X() 
>>> exec 'a=23' in vars(x) 
>>> x.a 
23 

這樣,你知道的exec不會污染一般的命名空間,以及任何被定義的類都將是可以作爲的x屬性。 幾乎使得exec忍受...... - )

0

使用the exec statement來定義你的類,然後實例吧:

exec solvertext1 
s = solver() 
answer = s.solve(problem) 
0

簡單的例子:

>>> solvertext1 = "def f(problem):\n\treturn len(problem)\n" 

>>> ex_string = solvertext1 + "\nanswer = f(%s)"%('\"Hello World\"') 

>>> exec ex_string 

>>> answer 
11 
相關問題