自定义with open打开文件
# 是使用上下文管理协议自定义open class 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
# 自定义range class 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 n for 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=None def 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 head def travellink(head): p=head.next while p is not None: print(p.length) p=p.next lst=[1,23,44,56,] head=createlink(lst) travellink(head) print(‘---------------‘) tail_head=createlinktail(lst) travellink(tail_head)