将字符串转换为对象Python [英] Converting String into Object Python

查看:355
本文介绍了将字符串转换为对象Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始学习Python几个星期前,我开始写一个基于文本的冒险游戏。我有一些麻烦找到一个好的方法来将字符串转换为类的实例,而不是使用eval(),我读过的是不安全的。下面是我的工作:

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."

如果输入是字符串,那么如何安全地将其作为类对象并访问data属性。描述?

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!

推荐答案

使用一个字典:

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

这篇关于将字符串转换为对象Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆