我在学习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可以在这种情况下使用。
其他回答
正如书中所说,我只把它用作临时占位符,也就是说,
# code that does something to to a variable, var
if var == 2000:
pass
else:
var += 1
然后填充var == 2000的场景。
老实说,我认为Python官方文档描述得很好,并提供了一些示例:
The pass statement does nothing. It can be used when a statement is required syntactically but the program requires no action. For example: >>> while True: ... pass # Busy-wait for keyboard interrupt (Ctrl+C) ... This is commonly used for creating minimal classes: >>> class MyEmptyClass: ... pass ... Another place pass can be used is as a place-holder for a function or conditional body when you are working on new code, allowing you to keep thinking at a more abstract level. The pass is silently ignored: >>> def initlog(*args): ... pass # Remember to implement this! ...
一个可以“按原样”使用的常见用例是重写一个类来创建一个类型(在其他方面与超类相同),例如。
class Error(Exception):
pass
因此,您可以引发并捕获Error异常。这里重要的是异常的类型,而不是内容。
Pass is usually helpful when you are writing code to design a game or something of that type , now as you proceed with the code , you would realize that , there are some functions you don't want to move ahead and want to leave it untouched and move further on with the code and then revisit the function later , but as you do so , the compiler would obviously thrown an error saying it isn't either recognized and all sorts of other things!! In this condition you use pass so that the compiler would simply neglect the function and move further on with the code !!
例如:
if __name__ = "__main__":
pass
print("Hello World!")
在这里,编译器将忽略if name部分,并按照指示打印Hello World !!
谢谢!
在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可以在这种情况下使用。