有办法区分这两个返回的值吗?
>>> sort([1, 2, 3])
None
>>> dict(a=1).get('b')
None第一个返回None,因为没有返回的值。第二个返回None作为返回值。
发布于 2014-07-28 21:04:44
返回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 功能是相同的。因此,即使通过检查函数本身,也无法区分它们。
发布于 2014-07-28 20:55:22
不,没有。以下函数都返回相同的值,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您无法区分这些函数返回的值,因为它们都返回相同的内容。
发布于 2014-07-28 20:59:07
如果你专门问dict.get()的事
sentinel = object()
dict(a=1).get("b", sentinel)编写良好的“查找”API可以这样工作(让您传递一个自定义的'not‘值),或者引发一些异常。
否则,好吧,不,None是None,就这样。
https://stackoverflow.com/questions/25004120
复制相似问题