如何将字符串转换为Python类对象?
给定一个字符串作为python函数的用户输入,如果当前定义的命名空间中有一个具有该名称的类,我想从中获取一个类对象。
示例
class Foobar:
pass
print eval("Foobar")
print type(Foobar)输出结果
__main__.Foobar <type 'classobj'>
将字符串转换为类对象的另一种方法如下
示例
import sys
class Foobar:
pass
def str_to_class(str):
return getattr(sys.modules[__name__], str)
print str_to_class("Foobar")
print type(Foobar)输出结果
__main__.Foobar <type 'classobj'>
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短