Skip to main content
 首页 » 编程设计

python之为什么我的程序要求我输入 self 的值

2025年05月04日20sharpest

我正在用 python 制作纸牌游戏。我使用了我在网上找到的一类堆栈的代码:

class Stack: 
 
  def __init__(self): 
         self.items = [] 
 
  def isEmpty(self): 
     return self.items == [] 
 
  def push(self, item): 
     self.items.insert(0,item) 
 
  def pop(self): 
     return self.items.pop(0) 
 
  def peek(self): 
     return self.items[0] 

当我运行它时一切正常,但是当我尝试调用任何行为时,我的程序要求我为自己传递一个值,就好像它是一个参数一样。我觉得我要疯了......

当这段代码运行时:

  Cards = [] 
  Cards = Stack() 
  Cards = Stack.push(15) 
  Cards = Stack.peek() 
  Cards = Stack.pop() 

当第 3 行运行时显示此错误:

TypeError: push() missing 1 required positional argument: 'item' 

当我像这样传入None的值时

Cards = Stack.push(None,15) 

我还有另一个错误:

self.items.insert(0,item) 
AttributeError: 'NoneType' object has no attribute 'items' 

请您参考如下方法:

在将Cards 声明为Stack 的一个实例后,您不再需要引用Stack。只需使用 卡片。

Cards = Stack() 
Cards.push(15) 
x = Cards.peek() 
y = Cards.pop() 

此外,第一行代码 Cards = [] 没有用,因为您会立即将 Cards 重新分配给其他东西。