Python 区分无返回值和无返回值
有没有办法区分这两个返回值Python 区分无返回值和无返回值,python,Python,有没有办法区分这两个返回值 >>> sort([1, 2, 3]) None >>> dict(a=1).get('b') None 第一个返回None,因为没有返回值。第二个返回None作为返回值。否,没有。以下函数都返回相同的值,None: def a(): return None # Explicitly return, explicitly with the value None def b(): return # Explicitl
>>> sort([1, 2, 3])
None
>>> dict(a=1).get('b')
None
第一个返回
None
,因为没有返回值。第二个返回None
作为返回值。否,没有。以下函数都返回相同的值,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
您无法区分这些函数返回的值,因为它们都返回相同的内容
进一步阅读:如果您特别询问dict.get(): 编写良好的“查找”API要么以这种方式工作(让您传递一个自定义的“未找到”值),要么引发一些异常
否则,不,
None
是None
,句点。一个函数返回None
,只是返回或允许执行到达函数的末尾基本上是一样的
考虑以下功能:
def func1():
return None
def func2():
pass
def func3():
return
如果我们现在分解函数的字节码(disdis
模块可以做到这一点),我们将看到以下内容
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
功能相同。因此,即使通过检查函数本身,也无法区分它们。
None
是None
我的朋友。如果要区分,除了返回值之外,还必须区分其他内容。谢谢你的详细回答
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