標籤:異常 with return pat ati type elf highlight path
自訂with open開啟檔案
# 是使用上下文管理協議自訂openclass Open(object): def __init__(self,filepath,mode=‘r‘,encoding=‘utf8‘): self.filepath=filepath self.mode=mode self.encoding=encoding def __enter__(self): self.f=open(self.filepath,mode=self.mode,encoding=self.encoding) return self.f def __exit__(self, exc_type, exc_val, exc_tb): print(‘別瞎寫‘) self.f.close() return True def __getattr__(self, item): return getattr(self.f,item)with Open(‘a.txt‘,‘w‘) as f: f.write(‘aaa‘) f.jdhlasufh # 觸發異常,照樣能寫
自訂range
# 自訂rangeclass MyRange(object): def __init__(self,start=0,end=None): self.start=start self.end=end def __iter__(self): return self def __next__(self): if self.start==self.end: raise StopIteration n=self.start self.start+=1 return nfor i in MyRange(2,7): print(i)
自訂棧
# 自訂棧class MyStack(list): def is_empty(self): return len(self)==0 def peek(self): return self[0-1] def size(self): return len(self) def push(self,item): return self.append(item)stackobj=MyStack((1,22,3,5))stackobj.push(998)print(stackobj)print(stackobj.peek())print(stackobj.size())print(stackobj.is_empty())
自訂鏈表
class Node(object): # 單個節點對象 def __init__(self,length): self.length=length self.next=Nonedef createlink(lst): # 建立鏈表 head=Node(0) for num in lst: p=Node(num) p.next=head.next head.next=p head.length+=1 return head # 建立的鏈表只要有個前端節點就可以代表整個鏈表def createlinktail(lst): # 建立尾插法鏈表 head=Node(0) tail=head for num in lst: p=Node(num) tail.next=p tail=p head.length+=1 return headdef travellink(head): p=head.next while p is not None: print(p.length) p=p.nextlst=[1,23,44,56,]head=createlink(lst)travellink(head)print(‘---------------‘)tail_head=createlinktail(lst)travellink(tail_head)
Python一些代碼