首页 > 解决方案 > 我无法理解 python 中的对象操作

问题描述

我尝试使用下面的代码使用 2 个堆栈来实现队列。

实用程序堆栈实现。

class Stack():
    def __init__(self,array = []):
        self.array = array

    def is_empty(self):
        return self.array == []

    def pop(self):
        if self.array == []:
            raise Exception('stack is empty')
        else:
            popped_element = self.array.pop()
            return popped_element

    def push(self,key):
        self.array.append(key)

    def top(self):
        return self.array[-1]

    def __repr__(self):
        return " ".join(list(map(str,self.array)))



if __name__ == "__main__":
    q = Stack()
    q.push(1)
    q.push(2)
    q.push(3)
    q.push(4)
    q.push(5)
    print(q.pop())
    print(q.pop())
    print(q.pop())
    q.push(10)
    print(q)
from stack import Stack
class TwoStackQueue1():
    def __init__(self):
        self.stack1 = Stack()
        self.stack2 = Stack()

    def enqueue(self,key):
        self.stack1.push(key)

    def dequeue(self):
        while(self.stack1.is_empty() != True):
            top = self.stack1.top()
            print("eval_dequeue",top)
            self.stack2.push(top)
            self.stack1.pop()


        if self.stack2.is_empty() == True:
            raise Exception("Queue is empty")
        else:
            top = self.stack2.pop()
            return top

    def is_empty():
        return self.stack1.is_empty() and self.stack2.is_empty()

if __name__ == "__main__":
    q = TwoStackQueue1()
    q.enqueue(1)
    q.enqueue(2)
    q.enqueue(3)
    q.enqueue(4)
    q.enqueue(5)
    print(q.stack1)
    print(q.dequeue())

当我尝试对队列执行上述操作时,我的代码陷入无限递归,因为我的堆栈的弹出操作不起作用。有人可以帮我弄清楚为什么我的代码(队列操作:- q.dequeue())陷入无限递归吗?谢谢。

标签: pythonclassobjectrecursion

解决方案


问题在于,由于您使用了可变的默认参数这一事实,您有效地使对象的内部状态成为单例。

换句话说,由于默认情况下您可以用来初始化 Stack 的数组是空列表,因此任何未来的实例都将不仅使用列表,而且将使用与所有先前的 Stack 实例相同的列表。

试试这个快速修复:

class Stack():
    def __init__(self,array=None):
        self.array = array or []
    ...

推荐阅读