将字符串转换为类名(从appengine数据存储到类)

2 投票
2 回答
813 浏览
提问于 2025-04-15 18:22

可能重复的问题:
Python有没有类似于Java的Class.forName()的功能?

我正在使用appengine开发一个应用程序。理想情况下,我想这样定义一个新的类型(叫做Recipe):

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

但是看起来在ListProperty中不能把"type"作为类的值。我在想,能不能不使用ListProperty,而是用ListStringProperty,把类名保存为字符串。不过,我该怎么把字符串转换成类名,这样我就可以像这样写:

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

提前谢谢你,
Jose

2 个回答

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 是通过“名字”来序列化类型的,所以有一些限制(基本上,类型必须在某个模块的顶层),但这比你自己去做序列化(尤其是反序列化)要方便得多。因为如果你自己处理类型名称,就相当于要重复 pickle 已经能帮你完成的工作!-)

撰写回答