Python中文
首页
教程
问答
标签
搜索
登录
注册
将字符串转换为对象Python
回答此问题可获得
20
贡献值,回答如果被采纳可获得
50
分。
<p>几周前我刚开始学习Python,我开始写一个基于文本的冒险游戏。我很难找到一个好的方法来将字符串转换为类的实例,而不是使用eval(),我已经读过它是不安全的。作为参考,以下是我的工作内容:</p> <pre><code>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." </code></pre> <p>如果输入是字符串,如何安全地将其设置为类对象并访问data属性.description?另外,如果我用完全错误的方式来做这件事,请随意提出一个替代方案!</p>
0 条评论
分类:
Python问答
请先
登录
后评论
默认排序
时间排序
1 个回答
匿名
1天前
擅长:python、mysql、java
<p>使用字典:</p> <pre><code>lookup = {'Room': Room(), 'Item': Item()} myinstance = lookup.get(input) if myinstance is not None: print myinstance.description </code></pre>
请先
登录
后评论
针对此问题:
更多的回答
关注
89
关注
收藏
1
收藏,
216
浏览
网友 提问于 2天前
相关Python问题
为什么我的神经网络模型的准确性不能在这个训练集上得到提高?
8 回答
为什么我的神经网络模型的权重变化不大?
8 回答
为什么我的神经网络的成本不断增加?
3 回答
为什么我的神经网络的输入pickle文件是19GB?
7 回答
为什么我的神经网络给属性错误?“非类型”对象没有属性“形状”
3 回答
为什么我的神经网络训练这么慢?
10 回答
为什么我的神经网络输出错误?
7 回答
为什么我的神经网络预测适用于MNIST手绘图像时是正确的,而适用于我自己的手绘图像时是不正确的?
7 回答
为什么我的神经网络验证精度比我的训练精度高,而且它们都是常数?
10 回答
为什么我的私人用户间聊天会显示在其他用户的聊天档案中?
6 回答
为什么我的积分的绝对误差估计值大于积分(使用scipy.integrate.nqad)?
7 回答
为什么我的积层回归器得分比它的组件差?
2 回答
为什么我的移动方法不起作用?
8 回答
为什么我的稀疏张量不能转换成张量
6 回答
为什么我的稀疏张量不能转换成张量?
10 回答
为什么我的程序“停止”了?
2 回答
为什么我的程序一直试图占用所有可用的CPU
6 回答
为什么我的程序不使用指定的代理
9 回答
为什么我的程序不工作(python帮助中的反向函数)?
2 回答
为什么我的程序不工作时,我使用多处理模块
4 回答