简体   繁体   English

我无法理解 python 中的对象操作

[英]I cannot understand object manipulation in python

I tried to implement a queue using 2 stacks using the code below.我尝试使用下面的代码使用 2 个堆栈来实现一个队列。

Utility Stack implementation.实用程序堆栈实现。

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())

when i tried to perform above operations on the queue , my code is getting stuck in infinite recursion because pop operation of my stack is not working .当我尝试对队列执行上述操作时,我的代码陷入无限递归,因为我的堆栈的弹出操作不起作用。 Can someone please help me figure out why my code (Queue operations:- q.dequeue()) is getting stuck in infinite recursion?有人可以帮我弄清楚为什么我的代码(队列操作:- q.dequeue())陷入无限递归? Thanks.谢谢。

The problem is that you have effectively made the inner state of your object a Singleton, by virtue of the fact that you used a mutable default argument .问题在于,由于您使用了可变默认参数,因此您已经有效地使对象的内部状态成为单例。

In other words, since the array you can initialize your Stack with is the empty list by default, any future instance will not just use an empty list, but will use the same list as all previous Stack instances.换句话说,由于默认情况下您可以用来初始化 Stack 的数组是空列表,任何未来的实例都不会只使用一个空列表,而是将使用所有以前的 Stack 实例相同的列表。

Try this quick fix:试试这个快速修复:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM