首页 > 解决方案 > 我如何处理python中的类?

问题描述

我不知道这里有什么问题,当我运行代码时没有任何反应!这是代码:

class Stack():
    "A container with a last-in-first-out (LIFO) queuing policy."

    def __init__(self,list=[]):
        self.list =list

    def push(self, item):
        "Push 'item' onto the stack"
        return self.list.append(item)

    def pop(self):
        "Pop the most recently pushed item from the stack"
        return self.list.pop()

s=Stack([6,7])

s.push(5)

我希望看到 s 被创建为列表 [6,7],然后将 5 添加到其中。但什么也没发生。我应该怎么办?

标签: python

解决方案


你的代码几乎没问题。你只需要打印一些东西就可以看到结果!

我只是想指出你有一个非常讨厌的错误。您正在使用变异类型作为默认参数!看这个例子:

s=Stack()
s.push(1)
s2=Stack()
print(s2.list) # should be empty

此代码实际打印[1]!请阅读这篇文章以获取更多信息。


推荐阅读