python - 将字符串转换为 Python 对象

标签 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):
        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?另外,如果我以完全错误的方式解决这个问题,请随时提出替代方案!

最佳答案

使用字典:

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

关于python - 将字符串转换为 Python 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18438953/

相关文章:

java - 面向对象的Java : External method calling with variable reference

c++ - 模板类数组定义不是类型名称、静态或枚举数 C++

Python:x==y 和 x.__eq__y() 返回不同内容的情况。为什么?

java - 创建对象与读取 Json

Python ctypes 指向结构指针的指针

python - 403 尝试读取用户时 Authorization_RequestDenied

python - 为什么 Python 对象可以有一个用整数表示的属性?

javascript - 动态添加到对象并在未定义时创建?

python - 将字符串列表写入 csv

python - Google App 引擎中的微服务