python進階(三) 內建函數getattr工廠模式

getattr()這個方法最主要的做用是實現反射機制。也就是說能夠經過字符串獲取方法實例。  傳入不一樣的字符串,調用的方法不同。
原型:getattr(對象,方法名)

 

舉個栗子:
pyMethod類下定義了三個方法, getattr(pyMethod(),'out%s'%str)()   傳入的方法名不一樣,調用不一樣的方法。些處方法名爲字符串。
這樣的話,想一想是否是用途不少,我能夠把方法名配置到文件中,讀取時使用getattr動態去調用。
#coding=utf-8

class pyMethod(object):
    def outstr(self):
        print('this is string')

    def outint(self):
        print('this is number')

    def outdate(self):
        print('this is date')


if __name__=="__main__":
    str = 'int'
    getattr(pyMethod(),'out%s'%str)()     
    str = 'str'
    getattr(pyMethod(),'out%s'%str)()
    str = 'date'
    getattr(pyMethod(),'out%s'%str)()

 

 getattr(pyMethod(),'out%s'%str)()  注意pyMethod()和最後的()   這裏之因此這麼寫pyMethod()加括號是實例化類對象,最後的括號,由於getattr函數反射後,是一個方法對象。

 

運行結果:python

C:\Python27\python.exe D:/weixin/python_getattr.py
this is number
this is string
this is date

Process finished with exit code 0

 

Linux and python學習交流1,2羣已滿.函數

Linux and python學習交流3羣新開,歡迎加入,一塊兒學習.qq 3羣:563227894學習

不前進,不倒退,中止的狀態是沒有的.this

一塊兒進步,與君共勉,spa

相關文章
相關標籤/搜索