Isinstance (OBJ,CLS)
Detects if obj is a class CLS object and is true, not false
class Foo (object): Pass = foo () isinstance (obj, foo)
Issubclass (Sub,super)
To detect if a sub class is a derived class of super class
class Foo (object): Pass class Bar (Foo): Pass Issubclass (Bar, Foo)
Exception handling
Grammar:
try: # fixed format with possible exception code block passexcept#except print (ex) # The exception can be printed out, optional pass
Type of exception
Attributeerror attempts to access a tree that does not have an object, such as foo.x, but Foo does not have a property xioerror input/output exception; it is basically impossible to open the file Importerror the module or package cannot be introduced is basically a path problem or name error Indentationerror syntax error (subclass); The code is not aligned correctly indexerror the subscript index exceeds the sequence boundary, for example, when X has only three elements, it attempts to access the X[5]keyerror Attempting to access a key that does not exist in the dictionary Keyboardinterrupt CTRL + C is pressed Nameerror use a variable that has not been assigned to the object SyntaxError Python code is illegal, the code cannot compile (personally think this is a syntax error, Wrong) TypeError the incoming object type is not compliant with the requirements Unboundlocalerror attempts to access a local variable that is not yet set, basically because another global variable with the same name causes you to think that you are accessing it valueerror a value that the caller does not expect , even if the type of the value is correct
Arithmeticerrorassertionerrorattributeerrorbaseexceptionbuffererrorbyteswarningdeprecationwarningenvironmenterroreoferror Exceptionfloatingpointerrorfuturewarninggeneratorexitimporterrorimportwarningindentationerrorindexerrorioerrorkeyboardint Erruptkeyerrorlookuperrormemoryerrornameerrornotimplementederroroserroroverflowerrorpendingdeprecationwarningreferenceerr Orruntimeerrorruntimewarningstandarderrorstopiterationsyntaxerrorsyntaxwarningsystemerrorsystemexittaberrortypeerrorunbou Ndlocalerrorunicodedecodeerrorunicodeencodeerrorunicodeerrorunicodetranslateerrorunicodewarninguserwarningvalueerrorwarni Ngzerodivisionerror
Instance:
' Hello ' Try : int (s1)except valueerror as E: print(e)
Exception exception
Universal exception, can catch any exception, but for special handling or alert exceptions need to be defined, and finally define exception this can ensure the normal operation of the program.
S1 ='Hello'Try: Int (s1)exceptkeyerror,e:Print('Key Error')exceptindexerror,e:Print('Index Error')exceptException, E:Print('Error')
Exception Other Structures:
Try : # main code block Pass except keyerror,e: # exception, the block is executed Pass Else : # The main code block executes, executes the block, i.e. no exception occurs Pass finally : # whether the exception or not, the final execution of the block Pass
To actively trigger an exception:
Try : Raise Exception (' wrong ... ') #raise active Trigger exception except Exception as E: Print (e)
Custom Exceptions:
classZidingyiexception (Exception):#Custom Exception name def __init__(Self, msg): Self.message=msgdef __str__(self):returnSelf.messageTry: RaiseZidingyiexception ('Custom Exceptions')exceptzidingyiexception as E:Print(e)
Assertion
# Assert Condition assert assert 1 = = 2
Reflection
The reflection feature in Python is provided by four built-in functions: Hasattr, GetAttr, SetAttr, delattr, respectively: detects if a member is included, gets a member, sets a member, deletes a member
classFoo (object):def __init__(self): Self.name='Wupeiqi' deffunc (self):return 'func'obj=Foo ()## # # Check if you have members # # #Hasattr (obj,'name') hasattr (obj,'func') ## # # # Get members # #GetAttr (obj,'name') getattr (obj,'func') ## # # # Set Members # #SetAttr (obj,' Age', 18) setattr (obj,'Show',LambdaNum:num + 1) ## # # # # Delete Members #Delattr (obj,'name') delattr (obj,'func')
Usage examples:
ImportSYSclassWebServer (object):def __init__(Self,host,port):#Constructor of the classSelf.host =host Self.port=PortdefStart (self):Print("Server is starting ...") defStop (self):Print("Server is stopping ...") defRestart (self): Self.stop () Self.start ()defTest_run (self,name):Print("Running ...", Name,self.host)if __name__=="__main__": Server= WebServer ('localhost', 333) Server2= WebServer ('localhost', 333) #print (sys.argv[1]) ifHasattr (server,sys.argv[1]): #获取成员, whether the member exists func= GetAttr (server,sys.argv[1])#Get Server.start memory addressFunc ()#Server.start ()
Related knowledge of the class