gpt4 book ai didi

python - 可能是 Python 中的 "kind-of"monad

转载 作者:IT老高 更新时间:2023-10-28 22:09:51 25 4
gpt4 key购买 nike

试图找到一种方法来清理我的一些代码。

所以,我的 Python 代码中有这样的内容:

company = None
country = None

person = Person.find(id=12345)
if person is not None: # found
company = Company.find(person.companyId)

if company is not None:
country = Country.find(company.countryId)

return (person, company, country)

阅读了有关 Haskell 单子(monad)的教程(特别是 Maybe),我想知道是否可以用另一种方式编写它。

最佳答案

company = country = None
try:
person = Person.find(id=12345)
company = Company.find(person.companyId)
country = Country.find(company.countryId)
except AttributeError:
pass # `person` or `company` might be None

EAFP

关于python - 可能是 Python 中的 "kind-of"monad,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8507200/

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