我在学习Python的过程中,我已经到了关于pass语句的部分。我正在使用的指南将其定义为通常用作占位符的空语句。
但我还是不太明白这是什么意思。pass语句将被使用的简单/基本情况是什么?为什么需要它?
我在学习Python的过程中,我已经到了关于pass语句的部分。我正在使用的指南将其定义为通常用作占位符的空语句。
但我还是不太明白这是什么意思。pass语句将被使用的简单/基本情况是什么?为什么需要它?
当前回答
在Python中,pass基本上什么都不做,但与注释不同的是,它不会被解释器忽略。所以你可以在很多地方利用它,把它变成占位符:
1:可以在课堂上使用
class TestClass:
pass
2:可以在循环语句和条件语句中使用:
if (something == true): # used in conditional statement
pass
while (some condition is true): # user is not sure about the body of the loop
pass
3:可用于功能:
def testFunction(args): # The programmer wants to implement the body of the function later
pass
当程序员暂时不想给出实现,但仍然想创建某个类/函数/条件语句以供以后使用时,通常使用Pass。由于Python解释器不允许出现空白或未实现的类、函数或条件语句,因此会给出一个错误:
IndentationError:期望一个缩进的块
Pass可以在这种情况下使用。
其他回答
在Python中,pass基本上什么都不做,但与注释不同的是,它不会被解释器忽略。所以你可以在很多地方利用它,把它变成占位符:
1:可以在课堂上使用
class TestClass:
pass
2:可以在循环语句和条件语句中使用:
if (something == true): # used in conditional statement
pass
while (some condition is true): # user is not sure about the body of the loop
pass
3:可用于功能:
def testFunction(args): # The programmer wants to implement the body of the function later
pass
当程序员暂时不想给出实现,但仍然想创建某个类/函数/条件语句以供以后使用时,通常使用Pass。由于Python解释器不允许出现空白或未实现的类、函数或条件语句,因此会给出一个错误:
IndentationError:期望一个缩进的块
Pass可以在这种情况下使用。
pass语句什么也不做。当语法上需要语句,但程序不需要操作时,可以使用它。
如果你想导入一个模块,如果它存在,并且忽略导入它,如果该模块不存在,你可以使用下面的代码:
try:
import a_module
except ImportError:
pass
# The rest of your code
如果您避免编写pass语句并继续编写其余代码,则会引发IndentationError,因为打开except块后的行没有缩进。
正如书中所说,我只把它用作临时占位符,也就是说,
# code that does something to to a variable, var
if var == 2000:
pass
else:
var += 1
然后填充var == 2000的场景。
假设您正在设计一个新类,其中包含一些您还不想实现的方法。
class MyClass(object):
def meth_a(self):
pass
def meth_b(self):
print "I'm meth_b"
如果您省略了传递,代码将无法运行。
然后你会得到一个:
IndentationError: expected an indented block
总之,pass语句不做任何特殊的事情,但它可以充当占位符,如下所示。