Customizing with Open File
# is a custom Openclass Open (object) using the context Management protocol: 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 (' Don't write blindly ') 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 # triggers an exception and can still write
Custom Range
# Custom 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)
Custom Stacks
# Custom Stack class Mystack (list): def is_empty (self): return len ==0 def Peek: 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 ())
Custom Linked List
Class Node (object): # single Node object def __init__ (self,length): self.length=length self.next=nonedef Createlink (LST): # Create linked list Head=node (0) for num in LST: p=node (num) p.next=head.next Head.next=p head.length+=1 return Head # creates a linked list that can represent the entire list of Def Createlinktail (LST) as long as there is a header node: # Create tail plug chain list 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 was 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 some code