问题
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!
回答1:
Use a dictionary:
lookup = {'Room': Room(), 'Item': Item()}
myinstance = lookup.get(input)
if myinstance is not None:
print myinstance.description
回答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.
来源:https://stackoverflow.com/questions/18438953/converting-string-into-object-python