创建类后,您只需添加搜索函数(方法):class Search: # The class does not include the search methods, at first
def __init__(self):
self.conditions = {}
def make_set_condition(option): # Factory function that generates a "condition setter" for "option"
def set_cond(self, value):
self.conditions[option] = value
return self
return set_cond
for option in ('price', 'name'): # The class is extended with additional condition setters
setattr(Search, option, make_set_condition(option))
Search().name("Nice name").price('$3').conditions # Example
{'price': '$3', 'name': 'Nice name'}
PS:此类有一个__init__()方法,该方法没有family参数(条件设置器在运行时动态添加,但添加到类中,而不是单独添加到每个实例中)。如果需要创建具有不同条件设置器的Search对象,则上述方法的以下变体起作用(__init__()方法有一个family参数):
^{pr2}$
如果您确实需要知道存储在其中的属性名称的搜索方法,只需使用set_cond.__name__ = option # Sets the function name
(就在return set_cond之前)。在此之前,方法Search.name具有以下名称:>>> Search.price
设置其__name__属性后,将获得一个不同的名称:>>> Search.price
以这种方式设置方法名可以使涉及该方法的错误消息更容易理解。在