zoukankan      html  css  js  c++  java
  • 反射&异常

    反射

    通过字符串映射或修改程序运行时的状态、属性、方法。python中的反射功能是由以下四个内置函数提供:hasattr、getattr、setattr、delattr,改四个函数分别用于对对象内部执行:检查是否含有某成员、获取成员、设置成员、删除成员。

    hasattr(obj,name_str) , 判断一个对象obj里是否有对应的name_str字符串的方法
    getattr(obj,name_str), 根据字符串去获取obj对象里的对应的方法的内存地址
    setattr(x,'y',v),设置作用  相当于 ``x.y = v''  相当于对象.'字符串'=方法    setattr(d,talk,bulk) #d.talk = bulk  动态装入bulk方法
    delattr

    class Dog(object):
        def __init__(self,name):
            self.name = name
    
        def eat(self):
            print("%s is eating..."%self.name)
    
    
    d = Dog("NiuHanYang")
    choice = input(">>:").strip()
    
    if hasattr(d,choice):
       getattr(d, choice)()
    
    #输入eat    --->choice=eat 调用  输出NiuHanYang is eating... 

    如果输入的chioce是静态属性  那么不用加上()调用

    传参数

    class Dog(object):
        def __init__(self,name):
            self.name = name
    
        def eat(self,food):
            print("%s is eating..."%self.name,food)
    
    
    d = Dog("NiuHanYang")
    choice = input(">>:").strip()
    
    if hasattr(d,choice):
      func = getattr(d, choice)
      func("包子")
    #输入eat  输出NiuHanYang   is eating...  包子

    动态装入bulk方法

    def bulk(self):  #在类外写入的一个方法
        print("%s is yelling...." %self.name)
    
    class Dog(object):
        def __init__(self,name):
            self.name = name
    
        def eat(self,food):
            print("%s is eating..."%self.name,food)
    
    
    d = Dog("NiuHanYang")
    choice = input(">>:").strip()
    
    if hasattr(d,choice):
        func = getattr(d, choice)
        func(‘包子’)
    else:
        setattr(d,choice,bulk) #相当于d.talk = bulk
        d.talk(d)  #调用bulk
       
    输入talk( 仅仅是字符串表示)
    输出 NiuHanYang  is yelling....

    删除

    delattr(d, choice)
    print(d.name)   -------->xx

    总结实例:

    class Foo(object):
     
        def __init__(self):
            self.name = 'wupeiqi'
     
        def func(self):
            return 'func'
     
    obj = Foo()
     
    # #### 检查是否含有成员 ####
    hasattr(obj, 'name')
    hasattr(obj, 'func')
     
    # #### 获取成员 ####
    getattr(obj, 'name')
    getattr(obj, 'func')
     
    # #### 设置成员 ####
    setattr(obj, 'age', 18)
    setattr(obj, 'show', lambda num: num + 1)
     
    # #### 删除成员 ####
    delattr(obj, 'name')
    delattr(obj, 'func')

    异常

    1、异常基础

    在编程过程中为了增加友好性,在程序出现bug时一般不会将错误信息显示给用户,而是现实一个提示的页面

    try:
        pass
    except Exception as e:
        pass

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

    while True:
        num1 = raw_input('num1:')
        num2 = raw_input('num2:')
        try:
            num1 = int(num1)
            num2 = int(num2)
            result = num1 + num2
        except Exception as e:
            print ('出现异常,信息如下:')
            print (e)

    2、异常种类

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

    AttributeError 试图访问一个对象没有的树形,比如foo.x,但是foo没有属性x
    IOError 输入/输出异常;基本上是无法打开文件
    ImportError 无法引入模块或包;基本上是路径问题或名称错误
    IndentationError 语法错误(的子类) ;代码没有正确对齐
    IndexError 下标索引超出序列边界,比如当x只有三个元素,却试图访问x[5]
    KeyError 试图访问字典里不存在的键
    KeyboardInterrupt Ctrl+C被按下
    NameError 使用一个还未被赋予对象的变量
    SyntaxError Python代码非法,代码不能编译(个人认为这是语法错误,写错了)
    TypeError 传入对象类型与要求的不符合
    UnboundLocalError 试图访问一个还未被设置的局部变量,基本上是由于另有一个同名的全局变量,
    导致你以为正在访问它

     实例:

    dic = ["wupeiqi", 'alex']
    try:
        dic[10]
    except IndexError as e:
        print (e)
    dic = {'k1':'v1'}
    try:
        dic['k20']
    except KeyError as e:
        print(“没有这个Key”,e)   ----->e 为错误的具体信息   没有这个key 'k20'
    s1 = 'hello'
    try:
        int(s1)
    except ValueError as e:
        print (e)

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

    # 未捕获到异常,程序直接报错
     
    s1 = 'hello'
    try:
        int(s1)
    except IndexError as e:
        print (e)

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

    s1 = 'hello'
    try:
        int(s1)
    except IndexError as e:
        print (e)
    except KeyError as e:
        print (e)
    except ValueError as e:
        print (e)
    s1 = 'hello'
    try:
        int(s1)
    except  (IndexError ,KeyError) as e:
        print (e)

    万能异常

    在python的异常中,有一个万能异常:Exception,他可以捕获任意异常  抓所有未知的错误

    Exception :抓住所有错误,不建议用

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

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

    s1 = 'hello'
    try:
        int(s1)
    except KeyError as e:
        print'键错误')
    except IndexError as e:
        print'索引错误')
    except Exception as e:
        print ('错误')

    3、异常其他结构

    try:
        # 主代码块
        pass
    except KeyError,e:
        # 异常时,执行该块(有错误)
        pass
    else:
        # 主代码块执行完,执行该块(正常运行)
        pass
    finally:
        # 无论异常与否,最终执行该块(必须执行)
        pass

    4、主动触发异常

    try:
        raise Exception('错误了。。。')
    except Exception as e:
        print (e)

    5、自定义异常

    class WupeiqiException(Exception):
     
        def __init__(self, msg):
            self.message = msg
     
        def __str__(self):   # __str__方法 在打印 对象 时,默认输出该方法的返回值。
            return self.message
            ###return "dfvfdbvfgbfb"
    try: 
    raise WupeiqiException('我的异常') #raise触发 msg=self.message='我的异常'
    except WupeiqiException as e:
    print (e)

    ----------》我的异常
    ###----------》dfvfdbvfgbfb

    6、断言

    # assert 条件
    assert 1 == 1
    assert 1 == 2

    try :
    code
    except (Error1,Erro2) as e:
    print e

    except Exception :抓住所有错误,不建议用

  • 相关阅读:
    SpringCloud项目中使用Nacos作为配置中心
    SpringCloud项目中使用Nacos作为注册中心
    idea创建maven多模块Spring Boot项目
    Java代码中对IP进行白名单验证
    idea配置jdk
    win10配置jdk1.8环境变量
    shell 提示符样式设置
    整数转换成中文读法的字符串
    比较三段式软件版本号大小
    Windows7安装 nginx+php 后访问.php文件出现 “No input file specified.” 的解决办法
  • 原文地址:https://www.cnblogs.com/hmm1995/p/10158589.html
Copyright © 2011-2022 走看看