我在学习Python的过程中,我已经到了关于pass语句的部分。我正在使用的指南将其定义为通常用作占位符的空语句。

但我还是不太明白这是什么意思。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! ...

如果你想导入一个模块,如果它存在,并且忽略导入它,如果该模块不存在,你可以使用下面的代码:

try:
    import a_module
except ImportError:
    pass
# The rest of your code

如果您避免编写pass语句并继续编写其余代码,则会引发IndentationError,因为打开except块后的行没有缩进。

最好和最准确的理解pass的方式是显式地告诉解释器什么都不做。以同样的方式输入以下代码:

def foo(x,y):
    return x+y

意思是“如果我调用函数foo(x, y),将标签x和y所代表的两个数字相加并返回结果”,

def bar():
    pass

意思是“如果我调用函数栏(),什么都不做。”

其他答案都很正确,但它也适用于一些不涉及占位的事情。

例如,在我最近编写的一段代码中,有必要对两个变量进行除法,并且除数可能为零。

c = a / b

显然,如果b为零,将产生一个ZeroDivisionError。在这种特殊情况下,在b为零的情况下,让c为零是理想的行为,所以我使用了以下代码:

try:
    c = a / b
except ZeroDivisionError:
    pass

另一种不太标准的用法是为调试器放置断点。例如,我想要一段代码在For语句的第20次迭代时进入调试器。在声明。所以:

for t in range(25):
    do_a_thing(t)
    if t == 20:
        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

首先,如果你想写一个block,像这样:

if statement:
    pass
for i in range(abc):
    pass
def func():
    pass

pass can是一个占位符。

其次,它可以让你与IDE“交流”: 当你想让你的IDE像这样递减缩进: 如果你的程序写在这里:

class abc(parent):
    def __init__(self, params):
        self.params=params
        if d:
            return
        else:
            return
        # cursor in there

现在你的缩进计数是2,但你希望它在下一行是1。 你可以输入一个pass,你的程序是这样的:

class abc(parent):
    def __init__(self, params):
        self.params=params
        if d:
            return
        else:
            return
        pass# cursor in there

并返回。它会让你快乐:

class abc(parent):
    def __init__(self, params):
        self.params=params
        if d:
            return
        else:
            return
        pass
    # cursor in there

现在缩进计数是1。