A, __ reduce __ () Introduction
When defining the extension type (ie type of use of Python C language API implementation), if you want to pickle them, you have to tell Python how to pickle them. __reduce__ After being defined, when the object is Pickle will be called. It either returns a string that represents the global name, Pyhton will find it and pickle, or return a tuple. The tuple contains 2-5 elements, comprising: a callable objects, when the call for reconstructing an object; a parameter element, used for the callable; is passed to __setstate__ state (optional); generating a elements in this list is iterated pickle (optional); iterator generating a dictionary elements are pickle (optional)
Second, the use case
class ServerError (UserWarning): # UserWarning user code generated warning DEF error (Self): # C language interface, error information into a string pickle return Self. __reduce__ () [. 1 ] # Returns (<class '__main __. ServerError '>, ( ' error')), it takes a slice DEF instance_name (name): the try : IF not isinstance (name, str): The raise ServerError ( " name must be a string " ) the except ServerError AS E: error=e.error()[0] print(error) instance_name ( 123 ) # action is: can customize the error message, the composition is returned to the front end json format