zoukankan      html  css  js  c++  java
  • Python反射、异常处理

    反射

    :字符串到对象属性的映射

    hasattr(obj,string),
    判断对象obj里面是否有叫string的字段或方法
    getattr(obj,string)
    获取obj对象里名叫string的字段或方法(如果重名先找字段)
    setattr(obj,y,v)
    设置属性或者方法obj.y = v
    delattr(obj,y)
    删除属性obj.y

    class Dog(object):
        def __init__(self,name):
            self.name = name
        def eat(self):
            print("%s is eating"%self.name)
    
    d = Dog("labuladuo")
    choice = input(">>").strip()
    #用户输入什么调用什么方法,用反射
    
    def bulk(self):
        print("%s is bulking"%self.name)
    
    if hasattr(d,choice):
        func = getattr(d,choice)
        func()
        #删除属性
        delattr(d,choice)
    else:
        #动态添加一个方法d.choice = bulk
        setattr(d,choice,bulk)
        d.bulk(d)
        #动态添加一个属性,如果该属性存在会报错
        setattr(d,choice,None)
        print(getattr(d,choice))

    反射为什么重要?
    动态的实现内存装配,通过字符串反射到内存对象,不用写一大堆if..else判断用户输入什么调用什么方法了,直接用反射

    异常处理

    Python中有很多异常,有的异常不能通过编译,例如:indentationError 这个不能catch

    低级版:抓住全部错误。不要这样用,自己搞着玩可以

    try:
        names[3]
        data["name"]
    except Exception as e:
        print("出错:",e)

    正常版:预料一些错误。一般的使用方式

    try:
        names[3]
        data["name"]
    except KeyError as e:
        print("没有该key",e)
    except IndexError as e:
        print(e)

    正常版低级形态:不知道是哪句代码出错,可以统一处理

    try:
        names[3]
        data["name"]
    except (KeyError,IndexError) as e:
        print("错误",e)

    终极出错大套餐:基本考虑各种情况,但是Exception不能catch缩进异常

    try:
        names[3]
        data["name"]
        open("aa.txt")
    except KeyError as e:
        print("没有该key",e)
    except IndexError as e:
        print("下标越界",e)
    except Exception as e:
        print("未知错误:",e)
    else:
        print("一切正常")
    finally:
        print("不管有没有错,都执行")

    自定义异常,例如别人调你的接口,别人触发你定义的异常

  • 相关阅读:
    C#命名约定:PascalCase和camelCase
    Windows8 App 四大名著完整本 隐私保护声明
    C#-编码习惯
    [转]C#之Console.Write()和Console.Read()及Console.Readline()的问题
    通过JavaScript动态输入计算
    在VS2008中加入ExtJS智能提示—>(方法一)
    在VS2008中加入ExtJS智能提示—>(方法二)
    (一)javascript面向对象:(1)类
    上证指数波浪分析2013/03/12
    Springsecurity源码Filter之HeaderWriterFilter(十二)
  • 原文地址:https://www.cnblogs.com/revo/p/7400060.html
Copyright © 2011-2022 走看看