python中的__call__函数

Posted wang-mengmeng

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python中的__call__函数相关的知识,希望对你有一定的参考价值。

简单实例:

class TmpTest:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __call__(self, x, y):
        self.x, self.y = x, y


a = TmpTest(1, 2)
a(4, 5)
print(a.x, a.y)
4 5

实战中应用:

import json
import requests

from common.RecordLog import log


class HttpRequests(object):
    def __init__(self):
        self.session = requests.Session()
        log.info(建立请求...)

    def send_request(self, method, url, params_type=form, data=None, **kwargs):
        method = method.upper()
        params_type = params_type.upper()
        if isinstance(data, str):
            try:
                data = json.loads(data)
            except Exception:
                    data = eval(data)
        if GET == method:
            response = self.session.request(method=method, url=url, params=data, **kwargs)
        elif POST == method:
            if params_type == FORM:
                log.info("开始发送请求,URL为:,请求数据为:".format(method, url, data))
                response = self.session.request(method=method, url=url, data=data, **kwargs)
            elif params_type == JSON:
                response = self.session.request(method=method, url=url, json=data, **kwargs)
            else:
                response = self.session.request(method=method, url=url, **kwargs)
        else:
            log.error("请求方法错误:request method ‘‘ error ! please check".format(method))
            raise ValueError(request method "" error ! please check.format(method))
        return response

    def __call__(self, method, url, params_type=form, data=None, **kwargs):
        return self.send_request(method, url,
                                 params_type=params_type,
                                 data=data,
                                 **kwargs)

    def close_session(self):
        self.session.close()
        try:
            log.info(关闭请求...)
            del self.session.cookies[JSESSIONID]
        except Exception:
            pass


request = HttpRequests()

 

以上是关于python中的__call__函数的主要内容,如果未能解决你的问题,请参考以下文章

python中的__call__函数

007_Python中的__init__,__call__,__new__

python特殊函数 __call__()

python特殊函数 __call__()

python中__call__方法解析

python __call__ 内置函数的使用