Python中Pass和None有什么区别 [英] What is the difference between Pass and None in Python

查看:110
本文介绍了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).

这篇关于Python中Pass和None有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆