저는 몇 주 전에 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 속성에 액세스 할 : 참고로, 여기에 내가 함께 일하고 있어요 무엇인가? 또한 내가 완전히 잘못된 방향으로 나아가고 있다면, 대안을 제시해 주시기 바랍니다!
사전에 특정 클래스 개체를 입력해야한다는 것을 알았으므로이 작업은 완벽하게 수행되었습니다. 감사! – user2717129
@ user2717129 여러분을 환영합니다! [대답을 수락] (http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)을 잊지 마세요 :) – TerryA
왜 downvote하시기 바랍니다 – TerryA