gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 18:50:35 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com