有没有办法区分这两个返回值?
>>> sort([1, 2, 3])
None
>>> dict(a=1).get('b')
None
第一个返回None
,因为没有返回值。第二个返回None
作为返回值。
答案 0 :(得分:6)
返回None
的函数,只是返回或允许执行到达函数的末尾基本上是相同的。
考虑以下功能:
def func1():
return None
def func2():
pass
def func3():
return
如果我们现在解散功能'字节码(dis
模块可以做到这一点),我们看到以下
func1():
2 0 LOAD_CONST 0 (None)
3 RETURN_VALUE
func2():
5 0 LOAD_CONST 0 (None)
3 RETURN_VALUE
func3():
8 0 LOAD_CONST 0 (None)
3 RETURN_VALUE
功能相同。因此,即使检查功能本身,也无法区分它们。
答案 1 :(得分:1)
不,没有。以下函数都返回相同的值None
:
def a(): return None # Explicitly return, explicitly with the value None
def b(): return # Explicitly return, implicitly with the value None
def c(): pass # Implicitly return, implicitly with the value None
您无法区分这些函数返回的值,因为它们都会返回相同的内容。
答案 2 :(得分:1)
如果您特别询问dict.get()
:
sentinel = object()
dict(a=1).get("b", sentinel)
写得好的“查找”API将以这种方式工作(让您传递自定义的“未找到”值)或引发一些异常。
否则,不,None
是None
,期间。