gpt4 book ai didi

python - Python中的空模式未充分利用?

转载 作者:IT老高 更新时间:2023-10-28 20:56:24 26 4
gpt4 key购买 nike

我时不时会遇到这样的代码:

foo = Foo()
...
if foo.bar is not None and foo.bar.baz == 42:
shiny_happy(...)

这在我看来,嗯,unpythonic。

在 Objective-C 中,您可以向 nil 发送消息并得到 nil 作为答案。我一直认为这很方便。当然可以实现 Null pattern in Python ,但是从谷歌给我的结果来看,这似乎不是很广泛使用。这是为什么呢?

或者甚至更好——让 None.whatever 返回 None 而不是引发异常会是个坏主意吗?

最佳答案

PEP 336 - Make None Callable提出了类似的功能:

None should be a callable object that when called with any arguments has no side effect and returns None.

它被拒绝的原因仅仅是“它被认为是一个在调用时 None 会引发错误的功能。”

关于python - Python中的空模式未充分利用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2014105/

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