反射

反射函數

 

1、getatter, hasatter, delatterspa

一、getattercode

 

class Teacher:
    dic = {'查看學生信息':' ','查看老師信息':' '}
    def show_student(self):
        print('show_student')
    def show_teacher(self):
        print('show_teacher')
    @classmethod
    def func(cls):
        print('hahaha')

ret1 = getattr(Teacher,'dic')  # 獲取類Teacher裏面的屬性dic,可等同於Teacher.dic 類也是對象
print(ret1)
ret2= getattr(Teacher,'func')  # 類.方法等同於Teacher.func
print(ret2)  # 打印的是地址
ret2()  # 地址加括號纔是執行代碼

 

運行結果:對象

{'查看老師信息': ' ', '查看學生信息': ' '}
<bound method Teacher.func of <class '__main__.Teacher'>>
hahaha

 

二、hasatterblog

  • getatter和hasatter屬於夫妻黨,先用hasatter判斷是否存在,再用getatter獲取對應的方法屬性
class Teacher:
    dic = {'查看學生信息':' ','查看老師信息':' '}
    def show_student(self):
        print('show_student')
    def show_teacher(self):
        print('show_teacher')
    @classmethod
    def func(cls):
        print('hahaha')
if hasattr(Teacher,'dic4'):  # 判斷是否在類Teacher中存在dic4,沒有則不會執行如下代碼,而且不會報錯
    ret = getattr(Teacher,'dic4')
    print(ret)
if hasattr(Teacher,'dic'):  # 判斷是否在類Teacher中存在dic,有則會執行如下代碼
    ret1 = getattr(Teacher,'dic')  # 獲取類Teacher裏面的屬性dic,可等同於Teacher.dic 類也是對象
    print(ret1)

 

運行結果:get

{'查看學生信息': ' ', '查看老師信息': ' '}

for循環,用戶交互與夫妻檔的結合:input

class Teacher:
    dic = {'查看學生信息':'show_student','查看老師信息':'show_teacher'}
    def show_student(self):
        print('show_student')
    def show_teacher(self):
        print('show_teacher')
    @classmethod
    def func(cls):
        print('hahaha')

alex = Teacher()  # 實例化
print(alex.show_student())  # 對象.方法函數
print(alex.show_teacher())  # 對象.方法函數
for k in Teacher.dic:
    print(k)  # 打印字典裏面的key
key = input('輸入需求:')  # 根據用戶需求是要顯示學生的仍是老師的
print(Teacher.dic[key])  # 打印你的需求。也能夠不直接打印而是經過下面的夫妻檔來完成
if hasattr(alex,Teacher.dic[key]):  # 夫妻檔判斷用戶輸入的需求是否存在
    func = getattr(alex,Teacher.dic[key])
    func()

運行結果:for循環

show_student
None
show_teacher
None
查看學生信息
查看老師信息
輸入需求:查看學生信息
show_student
show_student

 

三、小結class

經過反射能夠學到:循環

  • 對象名能夠獲取對象屬性和普通方法
  • 類名能夠獲取靜態屬性和類方法還有靜態方法
  • 普通函數方法的參數:self
  • 靜態方法:@staticmethod
  • 類方法:@classmethod
  • 屬性方法:@property
相關文章
相關標籤/搜索