【问题标题】:How to define a class in Python 2?如何在 Python 2 中定义一个类?
【发布时间】:2014-12-20 16:51:10
【问题描述】:

我刚刚开始学习 Python 中的类和对象,我在网上查找了为什么会出现错误的答案:“nameError, 'Bedroom' is not defined”并且有很多答案和解释,因为我必须定义类,但我只是看不出我个人做错了什么,这让我发疯,我知道这可能是一个非常愚蠢的错误,但我想你可以从中学习。

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."

【问题讨论】:

标签: python


【解决方案1】:

试试这个:

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()

现在您可以更轻松地添加带有自己描述的房间并适当地调整游戏节奏。

【讨论】:

  • 是的,帕德莱克我已经解决了这个问题,但更重要的是我不得不更改订单的事实让我感到困惑。感谢所有的帮助!
  • @KingSwan 如果您将初始化逻辑放在__init__ 中(例如,在Game.__init__ 内部:self.bedroom = Bedroom()),它的顺序无关紧要! :)
  • 哦,我明白了,这是有道理的,也感谢您的出色回答非常有帮助,是的,卧室(房间)最终会有一些特别的东西:P
  • @KingSwan 基本上它会以这种方式工作,因为编译器在调用函数之前不会自省,到那时 Bedroom 将被定义为不考虑顺序。
猜你喜欢
  • 2010-12-02
  • 1970-01-01
  • 1970-01-01
  • 2021-09-09
  • 2014-12-02
  • 2012-01-02
  • 1970-01-01
  • 2014-11-18
  • 1970-01-01
相关资源
最近更新 更多