2013-08-26 3 views
0

저는 몇 주 전에 Python을 배우기 시작했습니다. 그리고 나는 텍스트 기반 어드벤처 게임을 쓰기 시작했습니다. 나는 문자열을 클래스의 인스턴스로 변환하는 좋은 방법을 찾는데 어려움을 겪고있다. eval()을 사용하는 것 외에는 읽지 않은 것이 안전하지 않다.String을 Object 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

평가, 여기에 문제가되지 않습니다. 사용자가 제공 한 일부 문자열을 해석하기 위해 어떤 방식 으로든 Python을 사용한다면 문자열에 악의적 인 파이썬 코드가 포함될 수 있으므로 응용 프로그램이 안전하지 않습니다. 따라서 안전성과 단순성 중 하나를 선택해야합니다.