1.单例模式:
对于一个JDBC的连接池而言,如果来了一个用户,我们不需要重新创建一个连接池,只需要使用连接池里面的一个线程而已,因此在这种情况下,不需要重新创建一个新的对象,而只需要使用这个原有的对象。这种叫做单例模式。
class Foo: INSTANCE = None #静态字段,用类来访问 def __init__(self,name): self.name = name @classmethod def get_instance(cls): if cls.INSTANCE: return cls.INSTANCE else: obj = cls(‘Alex‘) cls.INSTANCE = obj return obj obj1 = Foo.get_instance() print (obj1) obj2 = Foo.get_instance() print (obj2)
返回结果:
<__main__.Foo object at 0x0147F8F0> <__main__.Foo object at 0x0147F8F0> #两个相同的内存地址
2.异常处理
try,except的完整代码块,如果try执行报错,执行exception,然后跳转到finally;如果try执行没有报错,跳转到else,最后执行finally
# try: # pass # except IOError as ex: # print (ex) # except ValueError as ex: # print (ex) # except IndexError as ex: # print (ex) # else: # pass # finally: # pass try: i = 123.0 int(i) except IOError as ex: print (ex) except ValueError as ex: print (ex) except IndexError as ex: print (ex) else: print (1234) finally: print (4567)
主动抛出异常
try: raise Exception("我的主动异常") i = 123.0 int(i) except IOError as ex: print (ex) except ValueError as ex: print (ex) except IndexError as ex: print (ex) except Exception as ex: print (ex) else: print (1234) finally: print (4567)
自定义异常:
class MyException(Exception): def __init__(self,msg): self.message = msg def __str__(self): return self.message + "ERROR" myex = MyException("我的异常") try: raise MyException("我的异常") except Exception as e: print (e)
时间: 2024-10-04 09:51:52