Skip to content Skip to sidebar Skip to footer

Converting String Into Object Python

I've just started learning Python a couple of weeks ago, and I started writing a text-based adventure game. I'm having some trouble finding a good way to convert strings into insta

Solution 1:

Use a dictionary:

lookup = {'Room': Room(), 'Item': Item()}
myinstance = lookup.get(input)
if myinstance isnotNone:
    print myinstance.description

Solution 2:

Eval is not the problem here, If you want a safe behavior you cannot input an untrusted string representing an instance without parsing it by yourself. If you use python in whatever way (eval or anything else) to interpret some string provided by a user then your application is not safe as the string can contain malicious python code. So you have to choose between safety and simpicity here.

Post a Comment for "Converting String Into Object Python"