我在学习Python的过程中,我已经到了关于pass语句的部分。我正在使用的指南将其定义为通常用作占位符的空语句。
但我还是不太明白这是什么意思。pass语句将被使用的简单/基本情况是什么?为什么需要它?
我在学习Python的过程中,我已经到了关于pass语句的部分。我正在使用的指南将其定义为通常用作占位符的空语句。
但我还是不太明白这是什么意思。pass语句将被使用的简单/基本情况是什么?为什么需要它?
当前回答
老实说,我认为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! ...
其他回答
正如书中所说,我只把它用作临时占位符,也就是说,
# code that does something to to a variable, var
if var == 2000:
pass
else:
var += 1
然后填充var == 2000的场景。
pass语句什么也不做。当语法上需要语句,但程序不需要操作时,可以使用它。
Pass指忽略…就是这么简单。如果给定的条件为真,并且下一个语句是通过的,它将忽略该值或迭代并继续执行下一行。
例子:
for i in range (1, 100):
if i%2 == 0:
pass
else:
print(i)
输出:输出1-100之间的所有奇数
这是因为一个偶数的模量等于零,因此它会忽略这个数字,继续下一个数字。由于奇数的模量不等于零,循环的else部分被执行并打印出来。
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 !!
谢谢!
除了“我不想要任何东西到这里”的“主要”用途之外,我刚刚发现了一个,假设gen是一个迭代器:
i = 0
obj = None
for i, obj in enumerate(gen):
pass
这将在一次传递中获得gen生成的最后一个对象和gen的长度。(有点类似于C语言中以分号结尾的while循环,仔细想想吧。)