python - 访问父类数据成员时出现打字错误

标签 python

我正在尝试使用两个堆栈创建一个队列,下面是我的代码:-

class Stack1(object):
    def __init__(self):
        super(Stack1, self).__init__()
        self.stack1 = []

    def push(self, item):
        self.stack1.append(item)
    def pop(self):
        self.popped_value = self.stack1.pop()       
        print("popped_value parent", self.popped_value)
        return self.popped_value
    def peek(self):
        try:
            return self.stack1[len(stack1)-1]
        except:
            print("Cannot peek into stack 1")
    def is_empty(self):
        if len(self.stack1) == 0:
            return True
        else:
            return False
    def display(self):
        print(self.stack1)

class Stack2(Stack1):
    def __init__(self):
        super(Stack2).__init__()
        self.stack2 = []        

    def push(self, popped):
        self.popped = popped
        return self.stack2.append(self.popped)
    def pop(self):
        return self.stack2.pop()
    def peek(self):
        try:
            return self.stack2[len(stack2)-1]
        except:
            print("Cannot peek into stack 2")
    def is_empty(self):
        if len(self.stack2) == 0:
            return True
        else:
            return False
    def display(self):
        print(self.stack2)
class DoubleStackQueue(Stack2):     
    def __init__(self):
        super(DoubleStackQueue, self).__init__()
        pass    
    def enqueue(self, item):
        self.item = item
        super(DoubleStackQueue, self).push(self.item)       
        Stack1.push(self.item)

dsq = DoubleStackQueue()
dsq.enqueue(2)

在这里,我尝试通过访问类 Stack1 的 push() 方法将一个项目推送到 stack1。但是,我收到以下错误:-

E:\>python dsq.py
Traceback (most recent call last):
  File "dsq.py", line 78, in <module>
    dsq.enqueue(2)
  File "dsq.py", line 75, in enqueue
    Stack1.push(self.item)
TypeError: push() missing 1 required positional argument: 'item'

你能帮我一下吗?

最佳答案

当您直接从类调用实例方法时,正如您通过调用 Stack1.push 所做的那样,您需要明确提供 self参数:

Stack1.push(self, self.item)

在您的通话中Stack1.push(self.item) self.item传递为 self参数,并且解释器会引发错误,因为它缺少其他必需的位置参数 item .

或者使用super :

super(Stack2, self).push(self.item)
<小时/>

这说:

  • 我相信你的代码相当困惑。我很确定Stack2.push方法应该负责调用 Stack1.push ,这样DoubleEndedQueue不需要执行双重调用。
  • 您可以替换 super(DoubleEndedQueue, self).push(self.item)只需 self.push.item ...自DoubleEndedQueue没有定义push方法父类(super class)Stack2将自动检查。

关于python - 访问父类数据成员时出现打字错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35826971/

相关文章:

python - 我的异步装饰器不断返回NoneType错误

Python & Sqlalchemy - 连接模式 -> 随机断开与远程服务器的连接

python - 修改数据框行 - Panda Python

python - 有效地删除 NumPy 中的行

Python 使用 curve_fit 拟合对数函数

python - 值错误: setting an array element with a sequence while using scale

python - 尝试绘制迭代但 plt.plot 为空

python - 如何使用 Tkinter 将小部件在窗口中垂直和水平居中?

Python 负索引差异

python - 获取 sympy 表达式的运算