To illustrate the question as simply as possible, below is a class and a list of objects of that class. The class has three attributes (category, name and color).
class Food:
def __init__(self,category,name,color):
self.category = category
self.name = name
self.color = color
food_list = [
Food('fruit','apple','red'),
Food('veg','carrot','orange'),
Food('fruit','tangerine','orange'),
Food('fruit','banana','yellow')
]
If I wanted to print the name of all items in the food_list that are in a particular category, I could write a function as below, and pass in the target value of the desired category (in this case 'veg').
# define the function
def print_category_items(target_value):
for food in food_list:
if food.category == target_value:
print(food.name)
# run the function
print_category_items('veg')
But if I wanted to search for items with a particular color, I'd have to write a new function, with 'food.color' hard coded in, instead of 'food.category'. Instead, I want to write a function that allows me to pass in both the attribute and the target value. It would take the following form (although the code below will obviously not work). In this example, I would be looking for all items with the color 'orange'.
# define the function
def print_items(attribute,target_value):
for food in food_list:
if food.attribute == target_value: # food.attribute will, of course, not work!
print(food.name)
# run the function
print_items(color,'orange')
Using lambda functions and the attrgetter function, I have tried far too many possibilities to reproduce here. But none of them work. Any advice very much appreciated.