python中__call__方法


在 Python 中提供了__call__ 方法,允許創建可調用的對象(實例)。如果類中實現了 __call__ 方法,則可以像使用函數一樣使用類。

例如簡單的封裝一個接口 get/post 方法:

 1 import requests
 2 
 3 class Run():
 4     def __init__(self):
 5         pass
 6 
 7     # __call__ 方法使用
 8     def __call__(self, url, method='post', data = None):
 9         if method == "get":
10             res = requests.get(url,data)
11         else:
12             res = requests.post(url,data)
13         return res
14 
15     
16 
17 if __name__ == "__main__":
18     url = "https://translate.google.com/"
19 
20     r = Run()
21     # 使用並且打印結果
22     print(r(url, 'get'))
23 
24 
25 # 打印結果: <Response [200]>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM