|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- class Stack:
- def __init__(self,start=[]):
- self.savings=[]
- for x in start:
- a = Stack()
- a.push(x)
- def isEmpty(self):
- return not self.savings
- def push(self,x):
- self.savings.append(x)
- def pop(self):
- self.savings.pop()
- def top(self):
- print(self.savings[-1])
- def bottom(self):
- print(self.savings[0])
- s = Stack([1,3])
- s.isEmpty()
- s.push(10)
- s.push(30)
- s.push(21)
- s.push(5)
- s.top()
- s.bottom()
- s.isEmpty()
- s.pop()
- s.top()
复制代码
代码第4行到第6行,如果按照这样调用的话,1与3并没有插入到这个一开始的列表中。
但是如果把这几行代码,改成答案里的:
for x in start:
self.push(x)
就能够成功。
请教一下为什么先实例化再调用不行,答案里的就可以呢?这个push不是一个方法吗,怎么前面要加self呢? 劳烦大家帮忙看下!
你的写法是把那些内容放进了a里面,并没有放到s里面。
而a在结束函数之后就消失了。所以相当于什么也没做。。。
|
|