python - 我如何处理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 添加到其中。但什么也没发生。我应该怎么办?
解决方案
你的代码几乎没问题。你只需要打印一些东西就可以看到结果!
我只是想指出你有一个非常讨厌的错误。您正在使用变异类型作为默认参数!看这个例子:
s=Stack()
s.push(1)
s2=Stack()
print(s2.list) # should be empty
此代码实际打印[1]
!请阅读这篇文章以获取更多信息。
推荐阅读
- javascript - 如何让我的 Discord Bot 在启动后立即发送消息?
- android - 使用 smb 协议将我的应用程序连接到本地网络
- r - R:将值保留在 r 数据帧的第一行中
- java - 如何使用 Java 生成 pem 格式的 privateKey?
- excel - 在没有 Powerquery 插件的情况下在 excel 2010 中打开时,Get/Transform 连接会发生什么
- c# - 从数据集中删除 SQL 链接
- java - 替代 Apache POI 中已弃用的 ExcelUtil.calculateColWidth()
- eclipse - Eclipse IDE Ctrl + Backspace 不起作用
- javascript - 通过javascript创建HTML元素不起作用
- kubernetes - 实现 RBAC,即使应用了 roleBinding,默认用户仍然保留访问权限