1

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 instances of a class, other than using eval(), which I've read isn't safe. For reference, here's what I'm working with:

class Room(object):
    """Defines a class for rooms in the 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 a 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 is a string, how do I safely make it a class object and access the data attribute .description? Also, if I'm going about this in entirely the wrong way, please feel free to suggest an alternative!

2 Answers 2

2

Use a dictionary:

lookup = {'Room': Room(), 'Item': Item()}
myinstance = lookup.get(input)
if myinstance is not None:
    print myinstance.description
Sign up to request clarification or add additional context in comments.

1 Comment

After figuring out that I had to enter my specific class objects in the dictionary, this worked perfectly. Thanks!
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.