gpt4 book ai didi

python - 如何区分默认参数和提供默认值的参数?

转载 作者:行者123 更新时间:2023-12-02 02:15:49 25 4
gpt4 key购买 nike

假设我有函数f,如下所示:

def f(c=None):
return 42 if c is None else c

那么我无法从此函数中获取 None 。现在您可能会想“好吧,只需检查另一个值,例如 2128.213 或其他值”,但是我无法从函数中获取该特定值,可以吗?

这就是为什么我想在可能的情况下区分 f()f(None) 以便我可以拥有

f() -> 42
f(None)-> None

请记住,这是一个简化的示例。实际上,它是一个类的 __init__(...) 函数,具有多个位置参数,我希望在本示例中将其处理为 c

最佳答案

这种情况下的常见做法是使用您不想返回的特定哨兵值。

class Sentinel():
pass


_sentinel = Sentinel()

# _sentinel = object() # this is the option too

def f(x=_sentinel):
return 42 if x is _sentinel else x

assert f() == 42
assert f(None) is None
assert f(5) == 5

关于python - 如何区分默认参数和提供默认值的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67202314/

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