NameError: name '' is not defined - Seen after trying to get input

NameError: name '' is not defined - Seen after trying to get input

我一直在尝试制作一款测试类游戏,以了解 类 及其运作方式。我的程序是:

    print('The Dark Tunnel 2: Electric Boogaloo')
    win = False
    class Room(object):

      def __init__(self, location):
        self.location = location

      def move(self):
        self.move = move
print(rooms[self.move])

      def look(self):
        self.look = look
        print(secrets[self.look])
    rooms = {'north': 'You are in a dark room.', 'south': 'You are in a bloody room.', 'west': 'You are in a wet room.', 'east': 'You are in a grungy room.'}
    secrets = {'north': 'There doesn\'t seem to be anything you missed.', 'south': 'There is an old coin by your feet.', 'west': 'There is too much water at your feet.', 'east': 'Is there someone behind those bars?'}
    while win == False:
      action = input('> ')
      if action in rooms:
        Room.move(action)
      else:
        Room.look(action)

输入 'north' 后,我认为会输出 'You are in a dark room' 我得到:

    Traceback (most recent call last):
    File "program.py", line 20, in <module>
    Room.move(action)
    File "program.py", line 9, in move
    self.move = move
    NameError: name 'move' is not defined

如果您希望 move 方法接受名为 move 的参数,则需要在定义方法时指定该参数:​​

def move(self, move):
    self.move = move

除了您的属性 move 需要与您的方法 move 具有不同的名称;否则,您将用提供的值替换 方法 self.move

def set_move(self, move):
    self.move = move

那么您需要使用 Room 实例 来调用它,而不是 class 本身。

r = Room('some location')
...
r.set_move(action)