gpt4 book ai didi

python - 如何整理参数功能以从枚举创建一组值?

转载 作者:行者123 更新时间:2023-12-03 18:33:25 24 4
gpt4 key购买 nike

给定一个 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's answer .

通用解决方案
使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'}

关于python - 如何整理参数功能以从枚举创建一组值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66050036/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com