python3學習之反射的四種基本方法

class Person(object):
    
    def __init__(self):
        pass
    def info(self):
        print('我是person類中的info方法')

 

1.getattr()方法函數

這個方法是根據字符串去某個模塊中尋找方法this

instantiation = reflect.Person()#先實例化
f = getattr(instantiation,'info')#使用getattr函數去尋找字符串的同名方法
f()#調用方法
輸出結果:我是person類中的info方法

2.hasattr()方法spa

這個方法是根據字符串去判斷某個模塊中該方法是否存在code

instantiation = reflect.Person()#先實例化
f = hasattr(instantiation,'info') print(f) 輸出結果:True

3.setattr()方法blog

這個方法是根據字符串去某個模塊中設置方法字符串

instantiation = reflect.Person()
f = setattr(instantiation,'exit','this is a exit method')
f2 = hasattr(instantiation,'exit')
print(f2)
輸出結果就是True

4.delattr()方法get

這個方法是根據字符串去某個模塊中刪除方法it

instantiation = reflect.Person()#實例化
f = delattr(instantiation,'exit')
f = hasattr(instantiation,'exit')
print(f)
輸出結果就是False
相關文章
相關標籤/搜索