• 面向对象编程相关


    判断类与对象关系

    isinstance(obj, cls) 

    判断对象obj是否是由cls类创建的

    #!/bin/bin/env python
    # -*-coding:utf-8 -*-
    
    class Foo:
        pass
    
    class Foo1(Foo):
        pass
    
    obj1 = Foo()        # 父类的对象
    obj = Foo1()        # 子类的对象
    
    print(isinstance(obj, Foo))      # 子类的对象也是父类的对象
    print(isinstance(obj, Foo1))     # 子类的对象
    print(isinstance(obj1, Foo1))    # 父类的对象不是子类的对象
    """
    True
    True
    False
    """
    # 如果对象obj是由Foo类创建的,那么就会返回True 否则返回False

    issubclass(Foo1, Foo)

    检查Foo1类是否是 Foo类的派生类

    class Foo:
        pass
    
    class Foo1(Foo):
        pass
    
    obj1 = Foo()        # 父类的对象
    obj = Foo1()        # 子类的对象
    
    print(issubclass(Foo1, Foo))        # Foo1是Foo的派生类,派生类也称子类
    
    # 输出结果:True

    异常处理

    1、异常基础

    在编程过程中为了增加友好性,在程序出现bug时一般不会将错误信息显示给用户,而是现实一个提示的页面,通俗来说就是不让用户看见大黄页!(这里的大黄页通常是写代码是用户访问网页,如果出现错误之后返回的一个黄色的报错页面通常称为:大黄页)

    try:
        # 主代码块
        pass
    except KeyError as e:
        # 异常时,执行该块
        pass
    else:
        # 主代码块执行完,执行该块
        pass
    finally:
        # 无论异常与否,最终执行该块
        pass

    需求:将用户输入的两个数字相加

    def ex_handling():
        """
        异常处理
        """
        while True:
            num1 = input("please enter a number: ").strip()
            num2 = input("please enter a number: ").strip()
            try:
                num1 = int(num1)
                num2 = int(num2)
                result = num1 + num2
                print("%d + %d = %d" % (num1, num2, result))
            except Exception as e:
                print('出现异常,信息如下:')
                print(e)
    
    ex_handling()
    
    # 输出结果:
        # please enter a number: 100
        # please enter a number: rain
        # 出现异常,信息如下:
        # invalid literal for int() with base 10: 'rain'
    except Exception as e

    2、异常种类

    python中的异常种类非常多,每个异常专门用于处理某一项异常!!!

    AttributeError 试图访问一个对象没有的树形,比如foo.x,但是foo没有属性x
    IOError 输入/输出异常;基本上是无法打开文件
    ImportError 无法引入模块或包;基本上是路径问题或名称错误
    IndentationError 语法错误(的子类) ;代码没有正确对齐
    IndexError 下标索引超出序列边界,比如当x只有三个元素,却试图访问x[5]
    KeyError 试图访问字典里不存在的键
    KeyboardInterrupt Ctrl+C被按下
    NameError 使用一个还未被赋予对象的变量
    SyntaxError Python代码非法,代码不能编译(个人认为这是语法错误,写错了)
    TypeError 传入对象类型与要求的不符合
    UnboundLocalError 试图访问一个还未被设置的局部变量,基本上是由于另有一个同名的全局变量,
    导致你以为正在访问它
    ValueError 传入一个调用者不期望的值,即使值的类型是正确的
    常用异常
    ArithmeticError
    AssertionError
    AttributeError
    BaseException
    BufferError
    BytesWarning
    DeprecationWarning
    EnvironmentError
    EOFError
    Exception
    FloatingPointError
    FutureWarning
    GeneratorExit
    ImportError
    ImportWarning
    IndentationError
    IndexError
    IOError
    KeyboardInterrupt
    KeyError
    LookupError
    MemoryError
    NameError
    NotImplementedError
    OSError
    OverflowError
    PendingDeprecationWarning
    ReferenceError
    RuntimeError
    RuntimeWarning
    StandardError
    StopIteration
    SyntaxError
    SyntaxWarning
    SystemError
    SystemExit
    TabError
    TypeError
    UnboundLocalError
    UnicodeDecodeError
    UnicodeEncodeError
    UnicodeError
    UnicodeTranslateError
    UnicodeWarning
    UserWarning
    ValueError
    Warning
    ZeroDivisionError
    更多异常
    # 测试AttributeError异常
    class Foo:
        def __init__(self, name):
            self.name = name
    
        def show(self):
            print(self.name)
    
    obj = Foo('rain')
    print(obj.name)
    print(obj.age)
    
    # 输出结果:
    # rain
    # AttributeError: 'Foo' object has no attribute 'age'
    # AttributeError 试图访问一个对象没有的属性,比如foo.x,但是foo没有属性x
    测试AttributeError异常
    lis = ['rain', 21, 'sunny', 22]
    print(lis[6])
    
    Traceback (most recent call last):
      File "E:/PyCharm4.5.2/PyCharm 文件/day8/exception_handling.py", line 40, in <module>
        print(lis[6])
    IndexError: list index out of range
    
    ————————————————————————————
    lists = ['rain', 21, 'sunny', 22]
    try:
        lists[5]
    except IndexError as ex:
        print('IndexError: %s' % ex)
        # IndexError: list index out of range
    IndexError
    dic = {'k1': 'v1'}
    print(dic['k2'])
    
    Traceback (most recent call last):
      File "E:/PyCharm4.5.2/PyCharm 文件/day8/exception_handling.py", line 64, in <module>
        print(dic['k2'])
    KeyError: 'k2'
    
    ————————————————————————————————————
    dic = {'k1': 'v1'}
    try:
        print(dic['k2'])
    except KeyError as e:
        print('KeyError: %s' % e)
        # KeyError: 'k2'
    KeyError

    对于上述实例,异常类只能用来处理指定的异常情况,如果非指定异常则无法处理。

    # 未捕获到异常,程序直接报错
    s1 = 'rain'
    try:
        int(s1)
    except IndexError as e:
        print(e)
    
    Traceback (most recent call last):
      File "E:/PyCharm4.5.2/PyCharm 文件/day8/exception_handling.py", line 86, in <module>
        int(s1)
    ValueError: invalid literal for int() with base 10: 'rain'
    
    
    ————————————————————————————————————————————————————————————————————————————————————————————————
    s1 = 'rain'
    try:
        int(s1)
    except ValueError as e:
        print(e)
        # invalid literal for int() with base 10: 'rain'

    所以,写程序时需要考虑到try代码块中可能出现的任意异常,可以这样写:

    s1 = 'rain'
    
    try:
        int(s1)
    except ValueError as e:
        print(e)
        # invalid literal for int() with base 10: 'rain'
    except KeyError as e:
        print(e)
    except IndexError as e:
        print(e)

    万能异常 在python的异常中,有一个万能异常:Exception,他可以捕获任意异常,即:

    s1 = 'rain'
    try:
        int(s1)
    except Exception as e:
        print(e)

    对于特殊处理或提醒的异常需要先定义,最后定义Exception来确保程序正常运行。

    s1 = 'rain'
    
    try:
        int(s1)
    except ValueError as e:
        print("值错误")
    except KeyError as e:
        print("不存在key")
    except IndexError as e:
        print("索引错误 ")
    except Exception as e:
        print(e)

    3、异常其他结构

    try:
        # 这一块才是最主要的逻辑处理块,所有的逻辑处理都是放在这里的
        pass
    except KeyError,e:# 如果出现KeyError错误,首先被他捕获,下面的except就不执行了
        pass
    except Exception,e:# 如果上面的错误没有找到就去,万能异常里找
        pass
    else:# 这里什么时候执行呢,逻辑代码里为出现异常这个代码快才执行
        pass
    finally: # 不管上面是否出现异常,最后执行完之后,这里永远执行!finally什么时候用?你上面执行一个操作,连接数据库,我这里就可以执行,断开数据库释放资源!(举例)
        pass
    
    '''
    上面的代码就是全部的异常处理的内容
    '''
    try:
        # 主代码块
        pass
    except Exception as e:
        # 异常时,执行该块
        pass
    else:
        # 主代码块执行完,执行该块
        pass
    finally:
        # 无论异常与否,最终执行该块
        pass

    4、主动触发异常

    try:
        raise Exception("主动触发异常。。。")
    except Exception as e:
        print(e)

    5、自定义异常

    当我们print “e”的时候是调用的__str__方法我们也就可以自己写一个异常了!

    # 自定义异常
    
    class RainException(Exception):     # 自己定义一个异常并继承Exception,除了自己定义的异常Exception的万能异常也可以使用
        def __init__(self, msg):
            self.message = msg
    
        def __str__(self):
            if self.message:
                return self.message         # 定义了错误了信息提示的错误
            else:
                return 'something error'    # 默认如果不传参数的时候提示的错误
    
    try:
        raise RainException('rain的异常')
    except RainException as e:
        print(e)
    
    # rain的异常

    6、断言

    assert 1 == 1
    print("hello assert")
    
    assert 1 == 2
    print("hello assert2")
    
    Traceback (most recent call last):
      File "E:/PyCharm4.5.2/PyCharm 文件/day8/exception_handling.py", line 150, in <module>
        assert 1 == 2
    AssertionError

    这个和  raise Exception('string')  只要你定义了raise肯定会报错
    这个一般什么时候使用,比如我写了一个软件,上面有些条款:
    你必须接受,你不接受我就不让你用!
  • 相关阅读:
    webpack4入门配置
    RequireJs的理解
    js一次控制 多个style样式
    vue中封装一个全局的弹窗js
    地理位置索引 2d索引
    索引属性 稀疏索引,定时索引
    索引属性 unique指定
    索引属性 name指定
    mongodb索引 全文索引使用限制
    mongodb索引 全文索引之相似度查询
  • 原文地址:https://www.cnblogs.com/yxy-linux/p/5627976.html
Copyright © 2020-2023  润新知