我制作了一个脚本,可以从booru画面下载。是否有任何替代方法可以使这个丑陋的if-elif子句看起来更简单,以防我想添加更多的booru图像板选择?感谢。
def runbooru(tags, limit=0, booru="Danbooru"):
tag = Danbooru(tags, limit)
if booru == "Danbooru":
tag = Danbooru(tags, limit)
elif booru == "Gelbooru":
tag = Gelbooru(tags, limit)
elif booru == "Rule34":
tag = Rule34(tags, limit)
elif booru == "Konachan":
tag = Konachan(tags, limit)
elif booru == "Yandere":
tag = Yandere(tags, limit)
elif booru == "Safebooru":
tag = Safebooru(tags, limit)
return tag
答案 0 :(得分:5)
使用字典:
processors = {f.__name__: f for f in (
Danbooru, Gelbooru, Konachan, Yandere, Safebooru)}
if booru in processors:
tag = processors[booru](tags, limit)
函数也是对象,您可以将它们存储在其他对象中,如字典和列表。
如果您认为Danbooru
是默认设置,那么您也可以在此使用dict.get()
:
processors = {f.__name__: f for f in (
Danbooru, Gelbooru, Konachan, Yandere, Safebooru)}
tag = processors.get(booru, Danbooru)(tags, limit)
如果Danbooru
值不是字典中的键,那么这将使用booru
函数。