0

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

3 Answers 3

3

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 ...
Sign up to request clarification or add additional context in comments.

1 Comment

As far as I know, while eval/exec work most people will warn you against them due to possible implications. I recommend using this Answer and just parsing out the arguments if you get passed arguments.
0

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().

Comments

0

You can use eval().

Example:

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

print ( eval("Rank") )

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.