class - Converting String into Object Python -
i've started learning python couple of weeks ago, , started writing text-based adventure game. i'm having trouble finding way convert strings instances of class, other using eval(), i've read isn't safe. reference, here's i'm working with:
class room(object): """defines class rooms in game.""" def __init__(self, name, unlocked, items, description, seen): self.name = name self.unlocked = unlocked self.items = items self.description = description self.seen = seen class item(object): """ defines class of items in rooms.""" def __init__(self, name, actions, description): self.name = name self.actions = actions self.description = description def examine(input): if isinstance(eval(input), room): print eval(input).description elif isinstance(eval(input), item): print eval(input).description else: print "i don't understand that."
if input string, how safely make class object , access data attribute .description? also, if i'm going in entirely wrong way, please feel free suggest alternative!
use dictionary:
lookup = {'room': room(), 'item': item()} myinstance = lookup.get(input) if myinstance not none: print myinstance.description
Comments
Post a Comment