hasattr\getattr\delattr------python
阿新 • • 發佈:2018-12-14
1、獲取類的屬性
class Teacher: dict = {'檢視學生資訊':'','檢視講師資訊':''} def show_student(self): print('show_student') def show_teacher(self): print('show_teacher') @classmethod def func(cls): print('hahha') ret2 = getattr(Teacher,'func') #呼叫類方法時,只需執行此方法即可 ret2() ret = getattr(Teacher,'dict') #呼叫類屬性,必須要列印 print(ret) >>>hahha >>>{'檢視學生資訊': '', '檢視講師資訊': ''}
2、hasattr總是與getattr連在一起使用:
class Teacher: dict = {'檢視學生資訊':'','檢視講師資訊':''} def show_student(self): print('show_student') def show_teacher(self): print('show_teacher') @classmethod def func(cls): print('hahha') if hasattr(Teacher,'func'): ret2 = getattr(Teacher,'func') ret2() ret = getattr(Teacher,'dict') print(ret) >>>hahha >>>{'檢視學生資訊': '', '檢視講師資訊': ''}
3、用物件呼叫屬性和方法:
class Teacher: dict = {'檢視學生資訊':'','檢視講師資訊':''} def show_student(self): print('show_student') def show_teacher(self): print('show_teacher') @classmethod def func(cls): print('hahha') alex = Teacher() func = getattr(alex,'show_student') func() >>>show_student