Python3自定义栈类
生活随笔
收集整理的這篇文章主要介紹了
Python3自定义栈类
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
一、自定義棧類(lèi):
創(chuàng)建Python文件,Stack
class Stack:"""這是一個(gè)自定義棧類(lèi)實(shí)現(xiàn)功能:入棧、出棧,修改棧大小等基本功能"""# 構(gòu)造方法def __init__(self, maxlen=10):self._content = []self._size = maxlenself._current = 0# 析構(gòu)方法def __del__(self):del self._content# 清空棧def clear(self):self._content = []self._current = 0# 判斷是否為空def isEmpty(self):return not self._content# 修改棧大小def setSize(self, size):if size < self._current:print('New size must ge' + str(self._current))returnself._size = size# 判斷棧是否已滿def isFull(self):return self._current == self._size# 入站def push(self, v):if self._current < self._size:self._content.append(v)self._current = self._current + 1else:print('Stack is Full!')# 出棧def pop(self):if self._content:self._current = self._current - 1return self._content.pop()else:print('Stack is empty!')# 顯示當(dāng)前棧元素def __str__(self):return 'Stack(' + str(self._content) + ',maxlen=' + str(self._size) + ')'# 顯示當(dāng)前棧大小def __len__(self):return self._currentif __name__ == '__main__':print('Please use the file as a module that stack.')二、自定義棧的有用法:
同文件夾下創(chuàng)建Python文件,Stack usage.py
from Stack import Stack # 導(dǎo)入自定義棧類(lèi)s = Stack() # 創(chuàng)建棧對(duì)象 print(s)s.push(5) # 入棧 s.push('a') print(s)print(s.pop()) # 出棧 print(s)s.push(8) s.push('c') print(s)s.setSize(8) # 修改棧上限大小 print(s)s.clear() # 清空棧 print(s)print(s.isEmpty()) # 判斷棧是否為空s.setSize(2) s.push(1) s.push(2) s.push(3) print(s)總結(jié)
以上是生活随笔為你收集整理的Python3自定义栈类的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 封装微信小程序提现到零钱
- 下一篇: python 栈的用法--学习