python中__call__方法

时间:2023-03-09 14:28:20
python中__call__方法

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

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

 import requests

 class Run():
def __init__(self):
pass # __call__ 方法使用
def __call__(self, url, method='post', data = None):
if method == "get":
res = requests.get(url,data)
else:
res = requests.post(url,data)
return res if __name__ == "__main__":
url = "https://translate.google.com/" r = Run()
# 使用并且打印结果
print(r(url, 'get')) # 打印结果: <Response [200]>