Python一些代码,代码,自定义with op
Python一些代码,代码,自定义with op
自定义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一些代码
相关内容
- Python调用GithubAPI并进行初步的数据分析,如何数据分析
- python 实现MQTT Client,python3,应用Python 实
- Python自动化学习--控制浏览器,,from selen
- Python之路【第二十七篇】:web服务器django,中国七十年之
- python自动化测试三部曲之untitest框架,python自动化测试
- python文件读取:遇见的错误及解决办法,python文件读取
- 解析prototxt文件的python库 prototxt-parser(使用parsy自定义文
- python----动态规划,python动态规划,不能放弃治疗,每天都
- Python之Pulsar框架使用,什么是框架,本文内容主要包含
- python关于type()的用法,typepython,如果按这种形式写ty
评论关闭