Marcus Pereira
Marcus Pereira

Reputation: 219

transform string in class instance?

I would like to turn string into a class to instantiate an object. Example:

A normal class:

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

Instantiating an object:

obj = Rank ()

Turning str in class ...

rank = 'Rank ()'
obj = rank

Sorry my english

Upvotes: 0

Views: 71

Answers (3)

galaxyan
galaxyan

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

Zroq
Zroq

Reputation: 8392

You can use eval().

Example:

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

print ( eval("Rank") )

Upvotes: 0

Philip Feldmann
Philip Feldmann

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

Related Questions