Python中Pass和None有什么区别
我个人想知道使用Pass和None之间的语义差异.我找不到执行上的任何区别.
I would personally like to know the semantic difference between using Pass and None. I could not able to find any difference in execution.
PS:我无法在SO中找到任何类似的问题.如果找到一个,请指出.
PS: I could not able to find any similar questions in SO. If you find one, please point it out.
谢谢!
pass
is a statement. As such it can be used everywhere a statement can be used to do nothing.
None
是NoneType的唯一实例)的关键字和恒定值.由于它是一个表达式,因此在需要该表达式的每个位置都有效.
None
is an atom and as such an expression in its simplest form. It is also a keyword and a constant value for "nothing" (the only instance of the NoneType
). Since it is an expression, it is valid in every place an expression is expected.
通常,pass
用于表示一个空的函数体,如以下示例所示:
Usually, pass
is used to signify an empty function body as in the following example:
def foo():
pass
此函数不执行任何操作,因为它的唯一语句是无操作语句pass
.
This function does nothing since its only statement is the no-operation statement pass
.
由于表达式也是有效的函数体,因此您也可以使用None
来编写它:
Since an expression is also a valid function body, you could also write this using None
:
def foo():
None
虽然函数的行为相同,但有一点不同,因为表达式(虽然为常数)仍将被求值(尽管会立即丢弃).
While the function will behave identically, it is a bit different since the expression (while constant) will still be evaluated (although immediately discarded).