1. Singleton mode:
For a JDBC connection pool, if a user comes in, we don't need to recreate a connection pool, just use one of the threads in the connection pool, so in this case there is no need to recreate a new object, just use the original object. This is called a singleton pattern.
classfoo:instance= None#static fields, using classes to access def __init__(self,name): Self.name=name @classmethoddefget_instance (CLS):ifCLS. INSTANCE:returnCLS. INSTANCEElse: obj= CLS ('Alex') CLS. INSTANCE=objreturnobjobj1=foo.get_instance ()Print(obj1) obj2=foo.get_instance ()Print(OBJ2)
return Result:
<__main__. Foo object at 0x0147f8f0><__main__. Foo object at 0x0147f8f0># two identical memory address
2. Exception handling
Try,except's complete code block, if the try executes an error, executes the exception, and then jumps to finally, if the try execution does not have an error, jumps to else, and finally executes a finally
#Try:#Pass#except IOError as ex:#print (ex)#except ValueError as ex:#print (ex)#except Indexerror as ex:#print (ex)#Else:#Pass#finally:#PassTry: I= 123.0Int (i)exceptIOError as ex:Print(ex)exceptValueError as ex:Print(ex)exceptIndexerror as ex:Print(ex)Else: Print(1234)finally: Print(4567)
Proactively throwing exceptions
Try: RaiseException ("my active anomaly.") I= 123.0Int (i)exceptIOError as ex:Print(ex)exceptValueError as ex:Print(ex)exceptIndexerror as ex:Print(ex)exceptException as ex:Print(ex)Else: Print(1234)finally: Print(4567)
Custom Exceptions:
classmyexception (Exception):def __init__(self,msg): Self.message=msgdef __str__(self):returnSelf.message +"ERROR"Myex= MyException ("My Exception")Try: RaiseMyException ("My Exception")exceptException as E:Print(e)
Python Object-oriented 6-singleton pattern, exception