如何整理参数功能以从枚举创建一组值?
给定一个Enum无法修改的对象,以及一个自定义Query类,该类应该生成Enum给定不同参数的值的编译:
from enum import Enum
class Fields(Enum):
a = ["hello", "world"]
b = ["foo", "bar", "sheep"]
c = ["what", "the"]
d = ["vrai", "ment", "cest", "vrai"]
e = ["foofoo"]
class Query:
def __init__(self, a=True, b=True, c=False, d=False, e=False):
self.query_fields = set()
self.query_fields.update(Fields.a.value) if a else None
self.query_fields.update(Fields.b.value) if b else None
self.query_fields.update(Fields.c.value) if c else None
self.query_fields.update(Fields.d.value) if d else None
self.query_fields.update(Fields.e.value) if e else None
可以获得一组自定义的query_fields,例如:
[出去]:
>>> x = Query()
>>> x.query_fields
{'bar', 'foo', 'hello', 'sheep', 'world'}
>>> x = Query(e=True)
>>> x.query_fields
{'bar', 'foo', 'foofoo', 'hello', 'sheep', 'world'}
问题:在Query初始化函数中,我们必须遍历每个类参数并执行类似的操作self.query_fields.update(Fields.a.value) if a else None,是否有其他方法可以在Query().query_fields不对每个参数进行硬编码的情况下实现相同的行为和输出?
回答
有关更通用的解决方案,请参见下文;对于Fields特定的和不需要的解决方案*args(或*members视情况而定......),请查看Tomer Shetah 的答案。
通用解决方案
为了使Query其他枚举更通用和可用,我将指定Field您想要的成员:
class Query:
#
def __init__(self, *members):
self.query_fields = set()
for member in members:
self.query_fields.update(member.value)
并在使用中:
>>> x = Query()
>>> x.query_fields
set()
>>> y = Query(Fields.a, Fields.c)
>>> y.query_fields
{'world', 'the', 'hello', 'what'}
如果您的默认值很常见,您可以将它们放在另一个变量中并使用它:
>>> fields_default = Fields.a, Fields.b
>>> z = Query(*fields_default)
>>> z.query_fields
{'foo', 'bar', 'world', 'hello', 'sheep'}