zoukankan      html  css  js  c++  java
  • Python 面向对象6

    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)

      

  • 相关阅读:
    ActiveMQ学习第八篇:Consumer
    ActiveMQ学习第七篇:Messaage
    线性判别分析LDA
    逻辑回归
    那些年,曾踩过的Spark坑
    HBase表创建、删除、清空
    python的多线程
    python的多进程
    python实现读写txt文件
    python的封包和解包
  • 原文地址:https://www.cnblogs.com/python-study/p/5739851.html
Copyright © 2011-2022 走看看