Today's Overview:
First, object-oriented advanced
1, Isinstance (OBJ,CLS) and Issubclass (Sub,super)
2, __setattr__,__getattr__,__delattr__
3, two times processing standard type (packing/authorization)
4, __setitem__,__getitem__,__delitem__
5, __str__,__repr__,__format
6, __next__,__iter__ implementation of the iterator protocol
7, __doc__
8. __del__ destructor
9, __enter__,__exit__
10, __call__
11, Metaclass Yuan class
Second, network programming
1. OSI Layer Seven
2. What is a socket?
3. Socket Work Flow
4. TCP-based sockets
5. UDP-based sockets
6. The difference between recv and recvfrom
7, sticky bag phenomenon
8, Socketserver solve concurrency
First, isinstance and Issubclass
Isinstance (obj,cls) checks if obj is an object of class CLS
Example:
Class Foo (object): pass obj = foo () isinstance (obj, foo)
Issubclass (sub, super) check if the sub class is a derived class of super class
Example:
Class Foo: passclass Go (foo): passprint (Issubclass (go,foo)) "Output true"
Second, __setattr__,__getattr__,__delattr__
#!/usr/bin/python#-*-coding:utf-8-*-#Special GetAttr is performed only if the attribute of the required class does not existclassFoo:def __init__(self,x): self.x=xdef __setattr__(self, Key, value): Self.__dict__[Key] = value#How to use them correctly #setattr (self,key,value) #进入无限递归 def __getattr__(self, item):Print('Getatt') def __delattr__(self, item):#del self.item into infinite recursionSelf.__dict__. Pop (item)#__setattr__ Modify or add attributes to executeg = Foo (10)Print(g.x)Print(g.__dict__)#setattr Rewrite, if __setattr__ write nothing, unless you manipulate the property dictionary directly, you can never assign a value#__delattr__ The Delete property is not triggeredG.__dict__['y'] = 2#You can modify the property dictionary directly in this way to complete the operation of adding or modifying propertiesPrint(g.__dict__) g.xxxxxx#use the. Invoke property, but the property does not exist but only when it is triggered" "output: Ten {' X ': ten} {' X ': ten, ' Y ': 2} getatt" "attr Examplecode Example三、二次 processing Standard type (packing/authorization)
Packaging: Python provides a standard data type and a rich set of built-in methods, but in many scenarios we need to customize our own data types based on standard data types, and add/rewrite methods that use the inheritance we just learned Derived knowledge (other standard types can be processed two times in the following way
#inherit all the properties of the list class to derive your own new such as Append and mid methodsclasslist (list):def __init__(self,item,tag=False): Super ().__init__(item) Self.tag=TagdefAppend (self, p_object):Print('derive all by themselves property + type check') if notisinstance (P_OBJECT,STR):RaiseTypeError ('%s must be str'%(p_object))defMid (self):Print('Custom Properties') Mid_index=len (self)//2returnSelf[mid_index]defClear (self):if notSelf.tag:RaisePermissionerror ('%s Permission') Else: Super (). Clear () Self.tag=Falsel= List ([All])Print(L) l.append ('4')Print(L)#L.tag = True#l.clear ()two secondary processing standard types based on inheritance implementation
Authorization: Authorization is a feature of packaging, packaging a type is usually some customization of the existing type, this practice can create new, modify or delete the functionality of the original product. Others remain as they are. The authorization process, that is, all updated functionality is handled by a part of the new class, but the existing functionality is granted to the object's default property.
The key to implementing authorization is to overwrite the __getattr__ method.
#!/usr/bin/python#-*-coding:utf-8-*-Import TimeclassFileHandle:def __init__(self,filename,mode='R', encoding='Utf-8'): Self.file= Open (filename,mode=mode,encoding=encoding)defWrite (self,line): t= Time.strftime ('%y-%m-%d%x') Self.file.write ('%s%s'%(t,line))def __getattr__(self, item):returngetattr (self.file,item) F1= FileHandle ('B.txt','w+', encoding='Utf-8') F1.write ('123123')#The following methods are used to find non-overriding methods through __getattr and reflection to the original method .f1.seek (0)Print(F1.read ()) F1.close ()Authorization Example 1
Python Automation Development-[eighth day]-object-oriented advanced chapter and network programming