2013-08-26 225 views
0

幾周前我剛剛開始學習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?另外,如果我以完全錯誤的方式討論這個問題,請隨時提出替代方案!

回答

1

使用詞典:

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

確定後,我不得不在字典中輸入特定的類對象,這工作完美。謝謝! – user2717129

+0

@ user2717129不客氣!不要忘記[接受答案](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work):) – TerryA

+0

爲什麼downvote請 – TerryA

0

評估和演示是不是問題就在這裏,如果你希望有一個安全問題,您可以不輸入表示實例,而無需通過自己進行解析不可信的字符串。如果您以任何方式(eval或其他)使用python來解釋用戶提供的某個字符串,那麼您的應用程序就不安全,因爲該字符串可能包含惡意的python代碼。所以你必須在這裏選擇安全性和簡單性。