Python导入类Stack

时间:2013-02-02 08:02:57

标签: python

在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方法push()必须使用Stack实例作为第一个参数调用(改为使用str实例)”

这究竟是什么意思?我不能推w? 如果是这样,我该怎么办才能将w推入堆栈?

2 个答案:

答案 0 :(得分:3)

你必须正确初始化Stack,我猜你忘记了括号:

stack = Stack()

答案 1 :(得分:2)

我认为问题出在上一行     stack = Stack 应该被替换     stack = Stack()