Converting String into Object Python

随声附和 提交于 2019-12-24 13:24:43

问题


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

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!


回答1:


Use a dictionary:

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



回答2:


Eval is not the problem here, If you want a safe behavior you cannot input an untrusted string representing an instance without parsing it by yourself. If you use python in whatever way (eval or anything else) to interpret some string provided by a user then your application is not safe as the string can contain malicious python code. So you have to choose between safety and simpicity here.



来源:https://stackoverflow.com/questions/18438953/converting-string-into-object-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!