Python 内置函数getattr()
2022/8/15 14:54:06
本文主要是介绍Python 内置函数getattr(),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
优点
- 可消除if...else
Python 面向对象中的反射
- 通过字符串的形式操作对象的属性,true or false
- Python 中一切皆为对象,所以只要是对象都可以使用反射
- 比如:实例对象、类对象、本模块、其他模块,因为他们都能通过 对a.属性 的方式获取、调用
hasattr def hasattr(*args, **kwargs): pass
- 返回对象是否具有具有给定名称的属性
getattr def getattr(object, name, default=None): pass
- 获取对象指定名称的属性
- 当属性不存在,则返回 default 值,如果没有指定 default 就会抛出异常
未使用反射前
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
这篇关于Python 内置函数getattr()的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-08有遇到过吗?同样的规则 Excel 中 比Python 结果大
- 2024-03-30开始python成长之路
- 2024-03-29python optparse
- 2024-03-29python map 函数
- 2024-03-20invalid format specifier python
- 2024-03-18pool.map python
- 2024-03-18threads in python
- 2024-03-14python Ai 应用开发基础训练,字符串,字典,文件
- 2024-03-13id3 algorithm python
- 2024-03-13sum array elements python