你可以使用字典和列表来解决这个问题。下面是一个示例的 Python 函数,可以根据指定的值来查找对象的属性:

def search_objects(objects, conditions, ignore=[]):
    result = []
    
    for obj in objects:
        match = True
        for key, value in conditions.items():
            if key not in ignore and getattr(obj, key) != value:
                match = False
                break
        if match:
            result.append(obj)
    
    return result

这个函数接受三个参数:

  • objects 是一個包含对象的列表。
  • conditions 是一個字典,其中键表示属性名称,值表示要查找的值。
  • ignore 是一個可選的列表,其中包含要忽略的属性名称。

函数遍歷每個对象,检查它的属性是否与指定的值匹配。如果所有属性都匹配,则将该对象添加到结果列表中。最后,函数返回结果列表。

你可以使用以下代碼來測試該函數:

class Person:
    def __init__(self, name, age, gender):
        self.name = name
        self.age = age
        self.gender = gender

people = [
    Person('Alice', 25, 'female'),
    Person('Bob', 30, 'male'),
    Person('Charlie', 35, 'male'),
    Person('Alice', 35, 'female')
]

conditions = {'name': 'Alice', 'age': 35}
ignore = ['age']

result = search_objects(people, conditions, ignore)
for person in result:
    print(person.name, person.age, person.gender)

该代碼将打印出 Alice 35 female,这是符合条件且忽略了 age 屬性的对象。

Python 对象属性查找函数:高效过滤和忽略属性