无需使用getattr(),如何动态访问对象的变量属性?
优雅访问Transaction对象的日期属性方案
以下是几种比getattr()更直观优雅的实现方式:
1. 使用属性映射字典
通过预定义允许的日期参数映射,代码可读性更强,还能快速拦截非法输入:
def analyzeTransaction(txObject, date='date1'): date_map = {'date1': txObject.date1, 'date2': txObject.date2} target_date = date_map[date] return target_date.year()
如果传入非date1/date2的参数,会直接抛出KeyError,便于快速定位问题。
2. 封装逻辑到Transaction类内部
把属性获取的逻辑封装到类的辅助方法中,符合面向对象的封装原则,外部函数代码更简洁:
首先给Transaction类添加辅助方法:
class Transaction: def __init__(self, date1, date2): self.date1 = date1 self.date2 = date2 def get_date(self, date_key='date1'): return getattr(self, date_key)
然后修改分析函数:
def analyzeTransaction(txObject, date='date1'): target_date = txObject.get_date(date) return target_date.year()
后续如果新增日期属性,只需修改Transaction类的get_date方法,无需改动外部分析函数。
3. 利用Python 3.10+的match-case语法
通过模式匹配明确处理合法参数,非法参数可自定义报错信息,逻辑更清晰:
def analyzeTransaction(txObject, date='date1'): match date: case 'date1': target_date = txObject.date1 case 'date2': target_date = txObject.date2 case _: raise ValueError(f"无效的日期参数:{date},仅支持'date1'或'date2'") return target_date.year()
内容的提问来源于stack exchange,提问作者Prospero
相关产品推荐
相关产品推荐

