1. 程式人生 > >python筆記(面向物件進階:反射)

python筆記(面向物件進階:反射)

一、反射:getattr,hasattr

1、getattr()和hasattr():

    class Teacher:
        dic = {'檢視學生資訊':'','檢視講師資訊':''}
        def show_student(self):
            print('show_student')
        def show_teacher(self):
            print('show_teacher')
        @classmethod
        def func(cls):
            print('哈哈哈哈')
    ret1 = getattr(Teacher,'dic')        #getattr()可執行字串形式的屬性
    ret2 = getattr(Teacher,'func')       #獲取到函式的地址
    ret2()
    if hasattr(Teacher,'dic1'):          #hasattr:有字串定義的方法或屬性就返回TURE
        ret = getattr(Teacher,'dic1')
    print(ret1)

輸出結果:

哈哈哈哈
{‘檢視學生資訊’: ‘’, ‘檢視講師資訊’: ‘’}

class Teacher:
    dic = {'檢視學生資訊':'show_student','檢視講師資訊':'show_teacher'}
    def show_student(self):
        print('student')
    def show_teacher(self):
        print('teacher')
    @classmethod
    def func(cls):
        print('哈哈哈哈')
long = Teacher()
key = input('輸入需求:')
if hasattr(long,Teacher.dic[key]):          #hasattr:有字串定義的方法或屬性就返回TURE
    ret = getattr(long,Teacher.dic[key])
    ret()

輸出結果:

輸入需求:檢視學生資訊
student

2、通過反射物件名獲取物件屬性和普通方法:類名獲取靜態屬性和類方法和靜態方法
(1)普通方法self
(2)靜態方法@staticmethod
(3)類方法@classmethod
(4)屬性方法@property

@isinstance(obj,cls)檢查obj是否是cls的物件

class A:pass
a = A()
print(isinstance(a,A))

輸出結果:

True

@issubclass(sub,super)檢查sub是否是super類的派生類(子類)
@反射:是用字串型別的名字去操作變數

(5)反射物件的屬性和方法

class B:
    name = 'xiaohai'
    age = 20
    def func(self):
        print('python')
b = B()
print(getattr(b,'name'))
ret = getattr(b,'func')
ret()

輸出結果:

xiaohai
python

(6)反射類的屬性和方法:classmethod,staticmethod

class C:
    name = 'xiaohai'
    age = 20
    @classmethod
    def func(cls):
        print('python')
print(getattr(C,'name'))
if hasattr(C,'func'):
    getattr(C,'func')()

輸出結果:

xiaohai
python

(7)反射模組的屬性和方法

import my_module  #自己定義的模組
print(getattr(my_module,'date'))

(8)反射自己模組中的變數

import sys
def wahaha():
    print('python')
year = 2018
getattr(sys.modules['__main__'],'wahaha')()
print(getattr(sys.modules['__main__'],'year'))

輸出結果:

python
2018

(9)setattr():設定修改變數delattr():刪除變數

class A:
    pass
a = A()
setattr(A,'name','alex')
setattr(a,'name','jing')
print(A.name)
print(a.name)
delattr(a,'name')
print(a.name)             #當物件中的屬性被刪除就在類的屬性中找相同屬性

輸出結果:

alex
jing
alex

在這裡插入圖片描述