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

标签 python class oop

我正在用 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 重新分配给其他东西。

关于python - 为什么我的程序要求我输入 self 的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55619345/

相关文章:

python - 将 C++ 中的数组操作转换为 Python

c++ - '类' : illegal use of this type as an expression how do I fix it?

css - 定位元素的同级子元素

python redis hget 字符串转字典

Python subprocess.call 似乎忽略参数

python - 为什么Python程序员不经常使用属性?

c++ - 错误 : variable or field 'PrintEntity' declared void void PrintEntity(Entity e);

c++ - 纯虚函数重载

java - 有没有办法在 Java 中将 boolean 类型指定为泛型?

oop - 为什么在 Kotlin 中 Stack<Int> 可以 push(null) 而 ArrayList<Int> 不能 add(null)?