Python----物件導向---反射的應用

來源:互聯網
上載者:User

標籤:strip()   ...   bsp   def   面向   post   sel   txt   get   

一、根據使用者的輸入,執行對象方法

例如:

 1 class Service: 2     def run(self): 3         while True: 4             cmd = input(‘>>: ‘).strip() 5             if hasattr(self, cmd): 6                 func = getattr(self, cmd) 7                 func() 8             print(cmd) 9 10     def get(self):11         print(‘get.......‘)12 13     def put(self):14         print(‘put.......‘)15 16 17 obj = Service()18 obj.run()19 20 結果為:21 >>: get22 get.......23 get24 >>: put25 put.......26 put27 >>: xxxx28 xxxx29 >>: 

有使用者選擇的方法的話執行,沒有的話就不會執行

還可以對上述代碼進行改進,如下:

 1 class Service: 2     def run(self): 3         while True: 4             inp = input(‘>>: ‘).strip() 5             cmds = inp.split() 6             print(cmds) 7             if hasattr(self, cmds[0]): 8                 func = getattr(self, cmds[0]) 9                 func(cmds)10 11 12     def get(self, cmds):13         print(‘get.......‘, cmds)14 15     def put(self, cmds):16         print(‘put.......‘, cmds)17 18 19 obj = Service()20 obj.run()21 22 結果為:23 24 >>: get a.txt25 [‘get‘, ‘a.txt‘]26 get....... [‘get‘, ‘a.txt‘]27 >>: put b.txt28 [‘put‘, ‘b.txt‘]29 put....... [‘put‘, ‘b.txt‘]30 >>: 

 

Python----物件導向---反射的應用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.