我在学习Python的过程中,我已经到了关于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语句不做任何特殊的事情,但它可以充当占位符,如下所示。


正如书中所说,我只把它用作临时占位符,也就是说,

# code that does something to to a variable, var
if var == 2000:
    pass
else:
    var += 1

然后填充var == 2000的场景。


一个可以“按原样”使用的常见用例是重写一个类来创建一个类型(在其他方面与超类相同),例如。

class Error(Exception):
    pass

因此,您可以引发并捕获Error异常。这里重要的是异常的类型,而不是内容。


除了用作未实现函数的占位符外,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

最好和最准确的理解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

在传递时使用断点。


Python在语法上要求代码块(在if, except, def, class等之后)不能为空。然而,空代码块在各种不同的上下文中都很有用,比如下面的例子,这是我见过的最常见的用例。

因此,如果在代码块中不希望发生任何事情,则需要一个传递以使该代码块不产生IndentationError。或者,任何语句(包括一个要求值的项,如Ellipsis字面量…)可以使用字符串(通常是docstring),但该传递清楚地表明,实际上不应该发生任何事情,也不需要实际计算并(至少暂时)存储在内存中。

Ignoring (all or) a certain type of Exception (example from xml): try: self.version = "Expat %d.%d.%d" % expat.version_info except AttributeError: pass # unknown Note: Ignoring all types of raises, as in the following example from pandas, is generally considered bad practice, because it also catches exceptions that should probably be passed on to the caller, e.g. KeyboardInterrupt or SystemExit (or even HardwareIsOnFireError – How do you know you aren't running on a custom box with specific errors defined, which some calling application would want to know about?). try: os.unlink(filename_larry) except: pass Instead using at least except Error: or in this case preferably except OSError: is considered much better practice. A quick analysis of all Python modules I have installed gave me that more than 10% of all except ...: pass statements catch all exceptions, so it's still a frequent pattern in Python programming. Deriving an exception class that does not add new behaviour (e.g., in SciPy): class CompileError(Exception): pass Similarly, classes intended as abstract base class often have an explicit empty __init__ or other methods that subclasses are supposed to derive (e.g., pebl): class _BaseSubmittingController(_BaseController): def submit(self, tasks): pass def retrieve(self, deferred_results): pass Testing that code runs properly for a few test values, without caring about the results (from mpmath): for x, error in MDNewton(mp, f, (1,-2), verbose=0, norm=lambda x: norm(x, inf)): pass In class or function definitions, often a docstring is already in place as the obligatory statement to be executed as the only thing in the block. In such cases, the block may contain pass in addition to the docstring in order to say “This is indeed intended to do nothing.”, for example in pebl: class ParsingError(Exception): """Error encountered while parsing an ill-formed datafile.""" pass In some cases, pass is used as a placeholder to say “This method/class/if-block/... has not been implemented yet, but this will be the place to do it”, although I personally prefer the Ellipsis literal ... in order to strictly differentiate between this and the intentional “no-op” in the previous example. (Note that the Ellipsis literal is a valid expression only in Python 3) For example, if I write a model in broad strokes, I might write def update_agent(agent): ... where others might have def update_agent(agent): pass before def time_step(agents): for agent in agents: update_agent(agent) as a reminder to fill in the update_agent function at a later point, but run some tests already to see if the rest of the code behaves as intended. (A third option for this case is raise NotImplementedError. This is useful in particular for two cases: Either “This abstract method should be implemented by every subclass, and there isn't a generic way to define it in this base class”, or “This function, with this name, is not yet implemented in this release, but this is what its signature will look like”)


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可以在这种情况下使用。


在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语句,这样它就不会干扰代码的其他部分。


你可以说pass意味着一个NOP(无操作)操作。看完这个例子,你就会清楚了:

C程序

#include<stdio.h>

void main()
{
    int age = 12;
  
    if( age < 18 )
    {
         printf("You are not adult, so you can't do that task ");
    }
    else if( age >= 18 && age < 60)
    {
        // I will add more code later inside it 
    }
    else
    {
         printf("You are too old to do anything , sorry ");
    }
}

现在你要怎么用Python写这个:

age = 12

if age < 18:

    print "You are not adult, so you can't do that task"

elif age >= 18 and age < 60:

else:

    print "You are too old to do anything , sorry "

但是您的代码会给出一个错误,因为在elif之后需要一个缩进的块。下面是pass关键字的作用。

age = 12

if age < 18:

    print "You are not adult, so you can't do that task"

elif age >= 18 and age < 60:
    
    pass

else:

    print "You are too old to do anything , sorry "

现在我想你们都清楚了。


老实说,我认为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! ...


Pass指忽略…就是这么简单。如果给定的条件为真,并且下一个语句是通过的,它将忽略该值或迭代并继续执行下一行。

例子:

for i in range (1, 100):
    if i%2 == 0:
        pass
    else:
        print(i)

输出:输出1-100之间的所有奇数

这是因为一个偶数的模量等于零,因此它会忽略这个数字,继续下一个数字。由于奇数的模量不等于零,循环的else部分被执行并打印出来。


pass用于避免Python中的缩进错误。

如果我们以C、c++和Java等语言为例,它们有这样的大括号:

 if(i==0)
 {}
 else
 {//some code}

但是在Python中,我们使用缩进代替大括号,所以为了避免这样的错误,我们使用pass。

记得你在做测验的时候

if(dont_know_the_answer)
    pass

示例程序,

for letter in 'geeksforgeeks':
    pass
print 'Last letter: ', letter

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

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

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


除了“我不想要任何东西到这里”的“主要”用途之外,我刚刚发现了一个,假设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 !!

谢谢!


首先,如果你想写一个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。


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