gpt4 book ai didi

Python if-else 困惑

转载 作者:太空宇宙 更新时间:2023-11-04 09:51:54 25 4
gpt4 key购买 nike

是否有更简洁的方法来创建 msg?对于每个事件(Ping、Pull request、Issue、Issue comment、Repo、Create、Delete、Pull requset requset、Push、Commit comment)是否有一个 if 子句来检查事件并根据其操作创建消息。

    data = request.json
event = request.headers['X-Github-Event']
msg = ""

...

# Pull request
elif event == "pull_request":
if data['action'] == "opened":
msg = PullRequest(data).opened()
elif data['action'] == "closed":
msg = PullRequest(data).closed()
elif data['action'] == "assigned":
msg = PullRequest(data).assigned()

# Issue
elif event == "issues":
if data['action'] == "opened":
msg = Issue(data).opened()
elif data['action'] == "reopened":
msg = Issue(data).reopened()
elif data['action'] == "closed":
msg = Issue(data).closed()
elif data['action'] == "labeled":
msg = Issue(data).labeled()
elif data['action'] == "assigned":
msg = Issue(data).assigned()
...

最佳答案

动态地这样做怎么样,例如

getattr(PullRequest(data), data['action'], lambda:None)()

总结

elif event == "pull_request":
getattr(PullRequest(data), data['action'], lambda:None)()
elif event == "issues":
getattr(Issue(data), data['action'], lambda:None)()

lambda:None 背后的想法是,如果 data['action'] 实际上不是 PullRequest(数据)问题(数据)


或者如果你不喜欢 if-else 语句,比如

callables = {
"pull_request":PullRequest,
"issues":Issue,
}

getattr(callables[event](data), data['action'], lambda:None)()

关于Python if-else 困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47464813/

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