Python一些代碼

來源:互聯網
上載者:User

標籤:異常   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一些代碼

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.