开发者

Convert string in Class name (from appengine datastore to class) [duplicate]

This question already has answers here: Closed 10 years ago.

Poss开发者_如何学编程ible Duplicate:

Does python have an equivalent to Java Class.forName()?

I'm using appengine to develop an application. Ideally I would like to define a new kind (called Recipe) like this:

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

However it seems that you cannot use "type" as the class value in ListProperty. I was thinking of instead of using ListProperty, using ListStringProperty and save the class names as strings. However, how do I convert a string to a class name, so I can write like this:

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

Thanks in advance,

Jose


I suggest you make ingredient a list of strings, populate it with the pickle.dumps of the types you're saving, and, upon retrieval, use pickle.loads to get a type object back.

pickle serializes types "by name", so there are some constraints (essentially, the types must live at the top level of some module), but that's way handier than doing your own serialization (and, especially, deserializaton) of the type names, which would essentially entail you repeating a bit of the work that pickle can already do on your behalf!-)


Maybe you can use eval, like this?

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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜