Python 导入类 Stack

3 投票
2 回答
3988 浏览
提问于 2025-04-17 14:31

在 util.py 文件中

class Stack:
  "A container with a last-in-first-out (LIFO) queuing policy."
  def __init__(self):
    self.list = []

  def push(self,item):
    "Push 'item' onto the stack"
    self.list.append(item)

  def pop(self):
    "Pop the most recently pushed item from the stack"
    return self.list.pop()

  def isEmpty(self):
    "Returns true if the stack is empty"
    return len(self.list) == 0

在 game.py 文件中

class Directions:
  NORTH = 'North'
  SOUTH = 'South'
  EAST = 'East'
  WEST = 'West'
  STOP = 'Stop'

  LEFT =       {NORTH: WEST,
                 SOUTH: EAST,
                 EAST:  NORTH,
                 WEST:  SOUTH,
                 STOP:  STOP}

  RIGHT =      dict([(y,x) for x, y in LEFT.items()])

  REVERSE = {NORTH: SOUTH,
             SOUTH: NORTH,
             EAST: WEST,
             WEST: EAST,
             STOP: STOP}

在 search.py 文件中

  from game import Directions
  s = Directions.SOUTH
  w = Directions.WEST
  e = Directions.EAST
  n = Directions.NORTH

  from util import Stack
  stack = Stack
  stack.push(w)

我在执行 stack.push(w) 时遇到了错误,提示“TypeError: unbound method push() must be called with Stack instance as first argument (got str instance instead)”。

这到底是什么意思?我不能把 w 放入栈中吗?

如果不能,那我该怎么做才能把 w 放入栈里呢?

2 个回答

2

我觉得问题出在前面那一行 stack = Stack 应该改成 stack = Stack()

4

你需要正确地初始化 Stack,我想你可能忘了加括号了:

stack = Stack()

撰写回答