将字符串转换为对象Python

将字符串转换为对象Python,python,class,object,Python,Class,Object,几周前我刚开始学习Python,我开始编写一个基于文本的冒险游戏。除了使用eval()之外,我在寻找将字符串转换为类实例的好方法时遇到了一些困难,我读到eval()是不安全的。作为参考,以下是我的工作内容: class Room(object): """Defines a class for rooms in the game.""" def __init__(self, name, unlocked, items, description, seen): sel

几周前我刚开始学习Python,我开始编写一个基于文本的冒险游戏。除了使用eval()之外,我在寻找将字符串转换为类实例的好方法时遇到了一些困难,我读到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."
如果输入是一个字符串,如何安全地将其设置为类对象并访问数据属性。说明?此外,如果我的做法完全错误,请随时提出替代方案

使用字典:

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

Eval不是这里的问题,如果您想要一个安全的行为,您不能输入一个表示实例的不受信任的字符串,而不亲自解析它。如果您以任何方式(eval或任何其他方式)使用python来解释用户提供的某些字符串,那么您的应用程序是不安全的,因为该字符串可能包含恶意python代码。所以你必须在安全性和简单性之间做出选择

在了解到我必须在字典中输入特定的类对象之后,这一点非常有效。谢谢@用户2717129不客气!别忘了:)