Python中的空返回是什么意思?

mic*_*imo 11 python

在GitHub上查看Python代码时,我看到了几个return没有价值的例子.例如:

    if hasattr(self, 'moved_away'):
        return
    # and here code continues
Run Code Online (Sandbox Code Playgroud)

空回报是什么意思?

Pad*_*ham 21

这意味着它会return None.您可以删除它return,它仍然会返回,None因为默认情况下,所有未在python中指定返回值的函数都将返回None.

在这种特殊情况下,它意味着如果对象具有属性'moved_away',代码将不再进一步,即使if语句评估为True ,也不会返回任何返回下面的代码.

因此,当您有一个条件想要退出循环时,您可以将其视为类似于循环中的break语句,而不会中断代码将继续进行评估.

if hasattr(self, 'moved_away'): # if this is True we return/end the function
        return
     # if previous statement was False we start executing code from here
Run Code Online (Sandbox Code Playgroud)


Har*_*mar 9

return 退出当前函数。

所以,在这里它将停止执行并返回None