我在学习Python的过程中,我已经到了关于pass语句的部分。我正在使用的指南将其定义为通常用作占位符的空语句。
但我还是不太明白这是什么意思。pass语句将被使用的简单/基本情况是什么?为什么需要它?
我在学习Python的过程中,我已经到了关于pass语句的部分。我正在使用的指南将其定义为通常用作占位符的空语句。
但我还是不太明白这是什么意思。pass语句将被使用的简单/基本情况是什么?为什么需要它?
当前回答
如果你想导入一个模块,如果它存在,并且忽略导入它,如果该模块不存在,你可以使用下面的代码:
try:
import a_module
except ImportError:
pass
# The rest of your code
如果您避免编写pass语句并继续编写其余代码,则会引发IndentationError,因为打开except块后的行没有缩进。
其他回答
pass语句什么也不做。当语法上需要语句,但程序不需要操作时,可以使用它。
除了“我不想要任何东西到这里”的“主要”用途之外,我刚刚发现了一个,假设gen是一个迭代器:
i = 0
obj = None
for i, obj in enumerate(gen):
pass
这将在一次传递中获得gen生成的最后一个对象和gen的长度。(有点类似于C语言中以分号结尾的while循环,仔细想想吧。)
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 !!
谢谢!
一个可以“按原样”使用的常见用例是重写一个类来创建一个类型(在其他方面与超类相同),例如。
class Error(Exception):
pass
因此,您可以引发并捕获Error异常。这里重要的是异常的类型,而不是内容。
在Python中,pass语句用于在语法上需要语句,但不希望执行任何命令或代码的情况。
pass语句是一个空操作;执行时什么也不发生。pass在你的代码最终要去的地方也很有用,但还没有写出来(例如,在存根中):
例子:
#!/usr/bin/python
for letter in 'Python':
if letter == 'h':
pass
print 'This is pass block'
print 'Current Letter :', letter
print "Good bye!"
这将产生以下结果:
Current Letter : P
Current Letter : y
Current Letter : t
This is pass block
Current Letter : h
Current Letter : o
Current Letter : n
Good bye!
如果字母的值是'h',上面的代码不会执行任何语句或代码。当您创建了一个代码块时,pass语句很有用,但不再需要它。
然后,您可以删除块中的语句,但让块保留pass语句,这样它就不会干扰代码的其他部分。