幾周前我剛剛開始學習Python,然後開始編寫基於文本的冒險遊戲。我遇到了一些麻煩,找到一種很好的方法來將字符串轉換爲類的實例,而不是使用eval(),我讀過的這個方法並不安全。作爲參考,這裏就是我的工作:將字符串轉換爲對象Python
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?另外,如果我以完全錯誤的方式討論這個問題,請隨時提出替代方案!
確定後,我不得不在字典中輸入特定的類對象,這工作完美。謝謝! – user2717129
@ user2717129不客氣!不要忘記[接受答案](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work):) – TerryA
爲什麼downvote請 – TerryA