Python Object-oriented 6-singleton pattern, exception

Source: Internet
Author: User

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): @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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.