我在学习Python的过程中,我已经到了关于pass语句的部分。我正在使用的指南将其定义为通常用作占位符的空语句。
但我还是不太明白这是什么意思。pass语句将被使用的简单/基本情况是什么?为什么需要它?
我在学习Python的过程中,我已经到了关于pass语句的部分。我正在使用的指南将其定义为通常用作占位符的空语句。
但我还是不太明白这是什么意思。pass语句将被使用的简单/基本情况是什么?为什么需要它?
当前回答
Pass只是空的表示代码。
例如,pass用于创建一个空类或函数,如下所示:
class Test:
pass
def test():
pass
但是,如果一个类或函数真的没有任何东西,甚至通过如下所示:
class Test:
# pass
def test():
# psss
出现如下错误:
SyntaxError:解析时意外的EOF
正如我之前所说,pass只是空的指示代码,所以如果在pass之后有一些代码,代码的工作方式如下所示:
class Test:
pass
x = "Hello World"
def test():
pass
return "Hello World"
print(Test.x) # Hello World
print(test()) # Hello World
其他回答
在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语句,这样它就不会干扰代码的其他部分。
假设您正在设计一个新类,其中包含一些您还不想实现的方法。
class MyClass(object):
def meth_a(self):
pass
def meth_b(self):
print "I'm meth_b"
如果您省略了传递,代码将无法运行。
然后你会得到一个:
IndentationError: expected an indented block
总之,pass语句不做任何特殊的事情,但它可以充当占位符,如下所示。
pass语句什么也不做。当语法上需要语句,但程序不需要操作时,可以使用它。
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 !!
谢谢!
除了用作未实现函数的占位符外,pass还可以用于填充if-else语句(“显式比隐式好”)。
def some_silly_transform(n):
# Even numbers should be divided by 2
if n % 2 == 0:
n /= 2
flag = True
# Negative odd numbers should return their absolute value
elif n < 0:
n = -n
flag = True
# Otherwise, number should remain unchanged
else:
pass
当然,在这种情况下,可能会使用return而不是赋值,但在需要突变的情况下,这种方法效果最好。
在这里使用pass特别有用,可以警告未来的维护者(包括您自己!)不要将多余的步骤放在条件语句之外。在上面的例子中,在特别提到的两种情况中设置了flag,但在其他情况中没有设置。如果不使用pass,未来的程序员可能会将flag = True移到条件之外,从而在所有情况下设置flag。
另一种情况是经常出现在文件底部的样板函数:
if __name__ == "__main__":
pass
在某些文件中,最好将其与pass一起保留,以便稍后更容易地进行编辑,并明确表示当文件单独运行时不期望发生任何事情。
最后,正如在其他回答中提到的,当异常被捕获时,什么都不做是很有用的:
try:
n[i] = 0
except IndexError:
pass