在 Python 中提供了__call__ 方法,允许创建可调用的对象(实例)。如果类中实现了 __call__ 方法,则可以像使用函数一样使用类。

例如简单的封装一个接口 get/post 方法:

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。
 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]>
扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄