python的栈--先进后出,就像杯子
作者:互联网
# coding = utf-8
class Stack(object):
"""栈"""
def __init__(self):
self.__list = []
def push(self, item):
"""添加一个元素item到栈顶"""
self.__list.append(item)
def pop(self):
"""弹出栈顶元素"""
if self.__list:
return self.__list.pop()
else:
return None
def peek(self):
"""返回栈顶元素"""
if self.__list:
return self.__list[-1]
else:
return None
def is_empty(self):
"""判断栈是否为空"""
return self.__list == []
def size(self):
"""返回栈的元素个数"""
return len(self.__list)
if __name__ == '__main__':
s = Stack()
print(s.pop())
s.push(1)
s.push(2)
print(s.pop())
print(s.size())
print(s.is_empty())
print(s.peek())
标签:__,.__,return,python,self,先进后出,list,--,def 来源: https://www.cnblogs.com/ClarenceSun/p/14765992.html