class HTTP(): def get(self, url, return_json=True): r = requests.get(url) if r.status_code !=200: if return_json: return {} else: return '' else: if return_json: return r.json() else: return r.text 用三元表达式可简化为: import requests class HTTP(): def get(self, url, return_json=True): r = requests.get(url) if r.status_code != 200: return {} if return_json else "" else: return r.json() if return_json else r.text 根据业务经验,状态码返回200,查询到结果才是常态,碰到状态码==200,就return,函数结束,不用进行后面的代码。进一步可简化为: class HTTP(): def get(self, url, return_json=True): r = requests.get(url) if r.status_code ==200: return r.json() if return_json else r.text return {} if return_json else ""