Reputation: 219
I would like to turn string into a class to instantiate an object. Example:
class Rank:
def __init__ (self):
print ('obj created ...')
obj = Rank ()
rank = 'Rank ()'
obj = rank
Sorry my english
Upvotes: 0
Views: 71
Reputation: 6121
try to use dict
class Rank:
def __init__ (self):
print ( 'obj created ...')
option = { 'rank': Rank }
obj = option['rank']
print 'init object'
obj()
init object
obj created ...
Upvotes: 3
Reputation: 8392
You can use eval().
Example:
class Rank:
def __init__ (self):
print ( 'obj created ...')
print ( eval("Rank") )
Upvotes: 0
Reputation: 8375
This is not the best practice, but you can execute strings by using exec()
.
For example:
rank = 'Rank()'
exec('obj = ' + rank)
exec
treats its parameter as if it was the line itself. So it'll basically execute obj = Rank()
.
Upvotes: 0