加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python中的__call__函数

发布时间:2020-12-20 10:54:48 所属栏目:Python 来源:网络整理
导读:简单实例: class TmpTest: def __init__ (self,x,y): self.x = x self.y = y def __call__ (self,y): self.x,self.y = x,ya = TmpTest(1,2 )a( 4,5 ) print (a.x,a.y) 4 5 实战中应用: import json import requests from common.RecordLog import log clas

简单实例:

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

    def __call__(self,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,data))
                response = self.session.request(method=method,data=data,**kwargs)
            elif params_type == JSON:
                response = self.session.request(method=method,json=data,**kwargs)
            else:
                response = self.session.request(method=method,**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,**kwargs):
        return self.send_request(method,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()

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读