如何在Python中编写可传入对象属性的通用查询函数?
解决方案
方法1:使用getattr()函数
这是Python内置的动态获取对象属性的方法,直接通过属性名字符串获取对应值,完全适配你的需求。
修改后的可运行函数代码:
def print_items(attribute, target_value): for food in food_list: # 用getattr动态获取对象的指定属性值 if getattr(food, attribute) == target_value: print(food.name) # 调用时需传入字符串形式的属性名 print_items('color', 'orange') print_items('category', 'fruit')
说明:getattr(food, attribute)会根据传入的attribute字符串参数,获取food对象对应名称的属性值,比如传入'color'时,效果等价于直接写food.color。
方法2:使用operator.attrgetter()
如果需要多次复用属性获取逻辑,attrgetter会更高效,它返回一个可调用函数,专门用于获取对象的指定属性:
from operator import attrgetter def print_items(attribute, target_value): # 创建获取指定属性的专用函数 get_attr = attrgetter(attribute) for food in food_list: if get_attr(food) == target_value: print(food.name) # 同样需传入字符串形式的属性名 print_items('color', 'orange')
关键注意点
- 调用函数时,属性名必须传字符串(如
'color'),不能直接写color——因为未定义名为color的变量,直接写会触发NameError。 - 若要避免传入不存在的属性名导致报错,可以给
getattr添加第三个参数作为默认值,例如getattr(food, attribute, None)。
内容的提问来源于stack exchange,提问作者fmex
相关产品推荐
相关产品推荐

