如何设计PersonFilter类实现Python对象的复杂条件过滤功能
设计思路
- 核心基于谓词组合实现:每个过滤条件本质是接收
People实例返回布尔值的判断函数,通过重载Python运算符实现&(与)、|(或)、~(非)的逻辑组合,无需硬编码各类条件分支,新增过滤维度时只需要新增对应判断方法即可,扩展性极强。 - 内置高频过滤谓词:提前封装职业、城市、年龄这类高频查询的类方法,调用时直接组合即可,无需重复编写判断逻辑。
- 统一对外暴露
matches方法:传入People实例直接返回是否符合过滤条件,get_people函数仅需调用该方法做判断即可,和原有业务逻辑兼容性高,改造成本极低。
代码实现
首先修改get_people函数适配新的过滤逻辑:
def get_people(person_filter=None): all_people = _load_people() # 原有加载缓存逻辑保持不变 # 未传入过滤条件时默认返回全量人员 if not person_filter: return all_people return [p for p in all_people if person_filter.matches(p)]
PersonFilter类实现:
class PersonFilter: def __init__(self, predicate=lambda p: True): self._predicate = predicate def matches(self, person): return self._predicate(person) # 重载与运算符 & def __and__(self, other): return PersonFilter(lambda p: self.matches(p) and other.matches(p)) # 重载或运算符 | def __or__(self, other): return PersonFilter(lambda p: self.matches(p) or other.matches(p)) # 重载非运算符 ~ def __invert__(self): return PersonFilter(lambda p: not self.matches(p)) # 内置常用过滤方法 @classmethod def profession_in(cls, professions): if isinstance(professions, str): professions = [professions] return cls(lambda p: p.profession in professions) @classmethod def city_in(cls, cities): if isinstance(cities, str): cities = [cities] return cls(lambda p: p.address.city in cities) @classmethod def age_gt(cls, age): return cls(lambda p: p.age > age) @classmethod def age_lt(cls, age): return cls(lambda p: p.age < age)
注意:你原代码的
People类__init__方法中存在笔误,profression拼写错误,需要修改为profession否则会报错。
使用示例
完全覆盖你提出的5个查询场景:
- 返回居住在纽约且职业为律师或工程师的所有人员
filter1 = PersonFilter.city_in("纽约") & PersonFilter.profession_in(["律师", "工程师"]) result = get_people(filter1)
- 返回居住在(纽约或西雅图)或职业为律师的所有人员
filter2 = PersonFilter.city_in(["纽约", "西雅图"]) | PersonFilter.profession_in("律师") result = get_people(filter2)
- 返回居住在(纽约或西雅图)且职业为律师的所有人员
filter3 = PersonFilter.city_in(["纽约", "西雅图"]) & PersonFilter.profession_in("律师") result = get_people(filter3)
- 返回居住在纽约且年龄大于40的所有人员
filter4 = PersonFilter.city_in("纽约") & PersonFilter.age_gt(40) result = get_people(filter4)
- 返回职业为会计或年龄大于30的所有人员
filter5 = PersonFilter.profession_in("会计") | PersonFilter.age_gt(30) result = get_people(filter5)
如果后续需要新增过滤维度,比如按邮编过滤,仅需在PersonFilter中新增对应类方法即可,无需修改get_people逻辑:
@classmethod def zipcode_eq(cls, zipcode): return cls(lambda p: p.address.zipcode == zipcode)
内容的提问来源于stack exchange,提问作者ThinkGeek
相关产品推荐
相关产品推荐

