将字符串转换为对象Python

2024-04-30 03:11:22 发布

您现在位置:Python中文网/ 问答频道 /正文

几周前我刚开始学习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."

如果输入是字符串,如何安全地将其设置为类对象并访问data属性.description?另外,如果我用完全错误的方式来做这件事,请随意提出一个替代方案!


Tags: 字符串nameselfactionsinputobjectdefeval
2条回答

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

使用字典:

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

相关问题 更多 >