2010-01-23 57 views
2

可能重複:
Does python have an equivalent to Java Class.forName()?將字符串轉換(從AppEngine上的數據存儲類)

我使用AppEngine上開發應用程序。理想我想定義一種新的(稱爲配方)是這樣的:

class Recipe(db.Model): 
    ingredients = db.ListProperty(type) 
    quantities = db.ListProperty(int) 

但是似乎你不能使用「類型」中的ListProperty類值。我想的不是使用ListProperty,而是使用ListStringProperty並將類名稱保存爲字符串。然而,如何將字符串轉換爲一個類名,這樣我就可以這樣寫:提前

str = "A" 
# convert str to class name in var class_str 
class_str().call_some_method() 

感謝,
何塞

+0

也許這個問題的答案會幫助你:[python是否具有與Java的Class.forName()?](http://stackoverflow.com/questions/452969/) – gclj5 2010-01-23 08:24:44

回答

0

也許你可以使用eval,這樣的嗎?

class Juice(object): 
    def amount(self): 
     print "glass of juice" 

juice = "Juice" 
eval(juice)().amount() 
# prints "glass of juice" 
1

我建議你ingredient字符串列表,與你保存類型pickle.dumps填充它,並經檢索,使用pickle.loads得到一個類型的對象了。

pickle序列化類型「按名稱」,所以有一些限制(基本上,該類型必須住在某些模塊的頂級),但是這不是做自己的序列化(和,尤其是方式更簡便, serializaton)的類型名稱,這基本上會導致你重複一下pickle已經可以代表你的工作!)

相關問題