1. 程式人生 > >Python一些代碼

Python一些代碼

range encoding odi 尾插 iteration elf tac pen size

自定義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)

  

Python一些代碼