1. 程式人生 > >python <11>反射與異常

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)