在类实例中转换字符串?

时间:2016-06-24 21:53:27

标签: python python-3.x

我想将字符串转换为一个类来实例化一个对象。例如:

正常班级:

class Rank:
     def __init__ (self):
         print ('obj created ...')

实例化对象:

obj = Rank ()

在课堂上转动str ......

rank = 'Rank ()'
obj = rank

对不起我的英文

3 个答案:

答案 0 :(得分:3)

尝试使用dict

class Rank:
     def __init__ (self):
         print ( 'obj created ...')

option = { 'rank': Rank }

obj = option['rank']

print 'init object'
obj()

init object
obj created ...

答案 1 :(得分:0)

这不是最佳做法,但您可以使用exec()执行字符串。 例如:

rank = 'Rank()'
exec('obj = ' + rank)

exec将其参数视为行本身。所以它基本上都会执行obj = Rank()

答案 2 :(得分:0)

您可以使用eval()。

示例:

class Rank:
     def __init__ (self):
         print ( 'obj created ...')

print ( eval("Rank") )