如何在Python 2中定义一个类?

时间:2014-10-24 19:23:23

标签: python

我刚开始学习Python中的类和对象,我在网上找到了为什么会出现错误的答案:“nameError,'卧室'未定义”并且有很多答案和解释我必须定义课程,但我只是看不出我个人做错了它让我疯了,我知道它可能是一个非常愚蠢的错误,但你想从中吸取教训。

prompt = "> "

class Start():
    print "Project Storm v0.01"
    print "Press Enter to Play"
    raw_input(prompt)
    bedroom = Bedroom(Room)

class Room():
    def enter(self):
        pass

class Bedroom(Room):
    def enter(self):
        print "You wake up dazed and confused with no memory of how you got here."
        print "You find yourself in a dark bedroom with a closed door and a small lamp on the side."

1 个答案:

答案 0 :(得分:0)

请改为尝试:

class Room():
    def enter(self):
        pass

class Bedroom(Room):
    def enter(self):
        print "You wake up dazed and confused with no memory of how you got here."
        print "You find yourself in a dark bedroom with a closed door and a small lamp on the side."

class Start(): # shouldn't this be Game() or something?
    print "Project Storm v0.01"
    print "Press Enter to Play"
    raw_input(prompt)
    bedroom = Bedroom(Room)
    # Bedroom has now been defined, so it knows what that is.

然而,这是一种奇怪的结构。给我一点时间,我可以提出更多可扩展的东西......

PROMPT = "> "

class Room():
    def __init__(self, msg):
        self.msg = msg
    def enter(self):
        print msg

class Bedroom(Room):
    pass
    # there's not actually anything special about this now, since all Room objects
    # will have a message. Maybe you have something special here?

class Game():
    def __init__(self):
        print "Project Storm v0.01"
        print "Press Enter to Play"
        raw_input(PROMPT) # all caps for constants
        self.rooms = {}
        self.rooms["bedroom"] = Bedroom("""You wake up dazed and confused with no memory of how you got here.
You find yourself in a dark bedroom with a closed door and a small lamp on the side.""")
    def start(self):
        self.rooms['bedroom'].enter()

if __name__ == "__main__":
    game = Game()
    game.start()

现在,您可以更轻松地添加具有自己描述的房间并适当地调整游戏速度。