编程语言
首页 > 编程语言> > Python 内置函数getattr()

Python 内置函数getattr()

作者:互联网

优点

 

Python 面向对象中的反射

 

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

标签:内置,get,Python,self,url,getattr,post,method,def
来源: https://www.cnblogs.com/QingshanY/p/16586822.html