您可以简单地添加搜索功能(方法)类创建后:
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
范围):
import types
class Search: # The class does not include the search methods, at first
def __init__(self, family):
self.conditions = {}
for option in family: # The class is extended with additional condition setters
# The new 'option' attributes must be methods, not regular functions:
setattr(self, option, types.MethodType(make_set_condition(option), self))
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
>>> o0 = Search(('price', 'name')) # Example
>>> o0.name("Nice name").price('$3').conditions
{'price': '$3', 'name': 'Nice name'}
>>> dir(o0) # Each Search object has its own condition setters (here: name and price)
['__doc__', '__init__', '__module__', 'conditions', 'name', 'price']
>>> o1 = Search(('director', 'style'))
>>> o1.director("Louis L").conditions # New method name
{'director': 'Louis L'}
>>> dir(o1) # Each Search object has its own condition setters (here: director and style)
['__doc__', '__init__', '__module__', 'conditions', 'director', 'style']
参考:http://docs.python.org/howto/descriptor.html#functions-and-methods http://docs.python.org/howto/descriptor.html#functions-and-methods
如果您确实需要知道存储它们的属性名称的搜索方法,您可以简单地将其设置为make_set_condition()
with
set_cond.__name__ = option # Sets the function name
(就在之前return set_cond
)。在执行此操作之前,方法Search.name
具有以下名称:
>>> Search.price
<function set_cond at 0x107f832f8>
设置其后__name__
属性,你会得到一个不同的名称:
>>> Search.price
<function price at 0x107f83490>
以这种方式设置方法名称可以使涉及该方法的可能错误消息更容易理解。