python <11>反射与异常

反射与异常加上类似于反射的文件的操作都将在下面以代码的形式体现。

一,反射

# _*_coding:utf-8_*_
# /usr/bin/env python3
# Author:book Miki



#  主要学习   getattr setattr hasattr delattr


def bulk(self):
    print('%s wangwangawng '%self.name)


class dog(object):
    def __init__(self,name):
        self.name = name

    def eat(self):
        print('%s eating....'%self.name)

d = dog('li')
choice = input('>>:')
if hasattr(d,choice):  # 判断是否有这个属性(方法,变量)
    func = getattr(d,choice)  # 返回内存地址
    func()
else:
    setattr(d,choice,bulk)




# 抓取异常 try: code = [] except IndentationError as e: # 抓取一个异常 print(e) except (IndentationError,KeyError) as e: print('抓取连个异常') except Exception as e: print('抓取所有异常') else: print('一切正常') # 一切正常的时候执行这个 finally: print('不管有错无措最后都会执行这个')

2.自定义异常

# _*_coding:utf-8_*_
# /usr/bin/env python3
# Author:book Miki





class liuerror(Exception):   # 自定义异常
    def __init__(self,name):
        self.name = name
    def __str__(self):   #  修改返回格式
        return 'asssddas'

try:
    raise liuerror('卧槽错了')
except liuerror as e:
    print(e)
原文地址:https://www.cnblogs.com/BookMiki/p/9998951.html