几周前我刚刚开始学习 Python,并开始编写基于文本的冒险游戏。除了使用 eval() 之外,我在找到一种将字符串转换为类实例的好方法时遇到了一些麻烦,我读过它是不安全的。作为参考,这是我正在使用的内容:
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."
如果输入是字符串,我如何安全地将其设为类对象并访问数据属性 .description?另外,如果我以完全错误的方式解决这个问题,请随时提出替代方案!