Secondary Processing Standard Type (Packaging)
Packaging: Python provides you with standard data types and a wealth of built-in methods. In fact, in many scenarios, we need to customize our own data types based on standard data types, and add/rewrite methods. This is what we just learned. The inheritance/derived knowledge of (other standard types can be processed in the following ways
#Based on inheritance and derivation to achieve secondary processing standard type #Derive the original list class class List(list): def append(self, p_object): #Customize a parent class that already exists in append if type(p_object) is str: #Specifies that only one string can be attached # self.append(p_object) #self calls its own method and falls into a recursive infinite loop super().append(p_object) #It is better to use super(), which is equivalent to list.append(p_object) #Call append () in the parent class, as long as you don't call your own, there will be no recursive infinite loop else : print ( ' only string types can be added ' ) def show_midlle(self): # Take the middle value in the list mid_index=int(len(self)/2 ) return self[mid_index] l2 =list( ' helloworld ' ) #The original system built-in list print (l2,type(l2)) # ['h','e','l','l','o','w',' o','r','l','d'] <class 'list'> l1 =List( ' helloworld ' ) #Use your own List inherited from list print (l1,type(l1)) # [ 'h','e','l','l','o','w','o','r','l','d'] <class '_main_.List'> # l1 The type is a list class print (l1. show_midlle()) # w l1.append(111111111111111111111) # Non-string This function is not allowed, the addition is unsuccessful #The parameter will be passed to p_object l1.append( ' SB' ) # is a string, which can be successfully added to print (l1)
Authorization: Authorization is a feature of packaging. Packaging a type is usually some customization of an existing type. This approach can create, modify or delete the functions of the original product. The others remain as they are. The process of authorization is that all updated functions are handled by some part of the new class, but the existing functions are authorized to the default properties of the object.
The key to implementing authorization is to override the __getattr__ method
import time class FileHandle: def __init__(self,filename,mode='r',encoding='utf-8'): self.file=open(filename,mode,encoding=encoding) def write(self,line): t=time.strftime('%Y-%m-%d %T') self.file.write('%s %s' %(t,line)) def __getattr__(self, item): return getattr(self.file,item) f1=FileHandle('b.txt','w+') f1.write('Hello') f1.seek(0) print(f1.read()) f1.close()
#_*_coding:utf-8_*_ __author__ = 'Linhaifeng' #Let's add b mode support import time class FileHandle: def __init__(self,filename,mode='r',encoding='utf-8'): if 'b' in mode: self.file=open(filename,mode) else: self.file=open(filename,mode,encoding=encoding) self.filename=filename self.mode=mode self.encoding=encoding def write(self,line): if 'b' in self.mode: if not isinstance(line,bytes): raise TypeError('must be bytes') self.file.write(line) def __getattr__(self, item): return getattr(self.file,item) def __str__(self): if 'b' in self.mode: res="<_io.BufferedReader name='%s'>" %self.filename else: res="<_io.TextIOWrapper name='%s' mode='%s' encoding='%s'>" %(self.filename,self.mode,self.encoding) return res f1=FileHandle('b.txt','wb') # f1.write('Hello ah ah ah ah') #Customized write, no need to convert it into binary to write, simple and atmospheric f1.write('Hello'.encode('utf-8')) print(f1) f1.close()
#exercise one class List: def __init__(self,seq): self.seq=seq def append(self, p_object): 'Derive your own append plus type checking, overwriting the original append' if not isinstance(p_object,int): raise TypeError('must be int') self.seq.append(p_object) @property def mid(self): 'Add your own method' index=len(self.seq)//2 return self.seq[index] def __getattr__(self, item): return getattr(self.seq,item) def __str__(self): return str(self.seq) l=List([1,2,3]) print(l) l.append(4) print(l) # l.append('3333333') #Error, must be int type print(l.mid) #Based on authorization, get the insert method l.insert(0,-123) print(l) #exercise two class List: def __init__(self,seq,permission=False): self.seq=seq self.permission=permission def clear(self): if not self.permission: raise PermissionError('not allow the operation') self.seq.clear() def __getattr__(self, item): return getattr(self.seq,item) def __str__(self): return str(self.seq) l=List([1,2,3]) # l.clear() #There is no permission at this time, throw an exception l.permission=True print(l) l.clear() print(l) #Based on authorization, get the insert method l.insert(0,-123) print(l)