Singleton mode, also known as the list mode, is a common software design pattern. When you apply this pattern, the class of the Singleton object must guarantee that only one instance exists. Many times the entire system only needs to have a global object, which helps us coordinate the overall behavior of the system. --Above from Wikipedia
There are many ways to achieve him, like Http://foofish.net/blog/93/python_singleton.
One simple way is to judge by a static field.
Class foo: instance = none def __init__ (self , name): self.name = name @ Classmethod def get_instance (Cls,name): # cls class name if cls.instance: return cls.instance else: obj =  CLS (name) cls.instance = obj return objobj1 = foo.get_instance (' Alex ') print (obj1.name) obj2 = foo.get_instance (' Bee ') print (obj2.name)-------- ----Alexalex
The second point is exception handling.
The General basic form is:
Try:passexcept Exception as Ex:pass
For example, note that if you want to catch different exceptions, Exception as ex needs to be written at the end, because he will put any exceptions in it.
While true:num1 = input (' NUM1: ') num2 = input (' num2: ') Try:li = [] li[100] num1 = Int (num1 ) num2 = Int (num2) result = Num1 + num2 except ValueError as Ex:print (ex) # str except IndexEr Ror as Ex:print (ex) # str except Exception as Ex:print (ex)
Another form of expression is try: Except. else.. Finally
else means that if there are no actions performed incorrectly, finally is the action that needs to be performed before all operations are completed.
650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M01/88/5F/wKioL1f0hlST43icAAJKLO2unKk325.png "title=" Capture.png "alt=" Wkiol1f0hlst43icaajklo2unkk325.png "/>
If you want to proactively execute an error, you can do so by raise, such as
>>> try:raise valueerror (' active error ') # self.message = ' Active error ' print (1234) except ValueError as Ex:print ( Ex) # strexcept Exception as Ex:print (ex) # __str__, return self.messageelse:passfinally:pass active error
Finally look at assert assert, if everything is OK, then proceed with the execution of the program behind him, or throw an exception
Like what
>>> A=100assert a>10print ("OK") assert a<40,print ("Oh Wrong") print ("wrong") Okoh Wrongtraceback (most Recent call last): File ' <input> ', line 4, in <module>assertionerror
This article is from the "Mapo Tofu" blog, please be sure to keep this source http://beanxyz.blog.51cto.com/5570417/1858820
Python Learning Notes-object-oriented (singleton mode and exception handling)