hasattr def hasattr(*args, **kwargs): pass
getattr def getattr(object, name, default=None): pass
class BaseRequest: req = requests.Session() def get(self, url): resp = self.req.get(url) print("==get==") return resp def post(self, url): resp = self.req.post(url) print("==post==") return resp def put(self, url): resp = self.req.put(url) print("==put==") return resp # 不使用反射的方法 def main(self, method, url): if method == "get": self.get(url) elif method == "post": self.post(url) elif method == "put": self.put(url)
# 使用反射的方法 def main_attr(self, method, url): if hasattr(self, method): func = getattr(self, method) func(url)
# 原始 def get(self, url, **kwargs): ''' 定义get方法 ''' response = requests.get(self.host + url, **kwargs, timeout=self.timeout, verify=False) return response def post(self, url, **kwargs): ''' 定义post方法 ''' response = requests.post(self.host + url, **kwargs, timeout=self.timeout, verify=False) return response # 优化 def main_http(self, method, url, **kwargs): # 判断对象是否有对应的方法 if hasattr(self, method): # 获取对应的方法 func = getattr(self, method) # 执行方法,且获取返回值 res = func(url, **kwargs) return res