如何使用pass语句?

问题:如何使用pass语句?

我正在学习Python,并且已经到达有关该pass语句的部分。我正在使用的指南将其定义Null为通常用作占位符的语句。

我仍然不完全明白那是什么意思。有人可以告诉我一个简单/基本的情况下使用该pass语句以及为什么需要该语句吗?

I am in the process of learning Python and I have reached the section about the pass statement. The guide I’m using defines it as being a Null statement that is commonly used as a placeholder.

I still don’t fully understand what that means though. Can someone show me a simple/basic situation where the pass statement would be used and why it is needed?


回答 0

假设您正在使用尚未实现的某些方法设计一个新类。

class MyClass(object):
    def meth_a(self):
        pass

    def meth_b(self):
        print "I'm meth_b"

如果您不使用pass,则代码将无法运行。

然后,您将获得:

IndentationError: expected an indented block

总而言之,该pass语句没有什么特别的,但是可以充当占位符,如此处所示。

Suppose you are designing a new class with some methods that you don’t want to implement, yet.

class MyClass(object):
    def meth_a(self):
        pass

    def meth_b(self):
        print "I'm meth_b"

If you were to leave out the pass, the code wouldn’t run.

You would then get an:

IndentationError: expected an indented block

To summarize, the pass statement does nothing particular, but it can act as a placeholder, as demonstrated here.


回答 1

Python有句法的要求,即代码块(后ifexceptdefclass等等)不能为空。但是,空代码块在各种不同的上下文中都很有用,例如下面的示例,这是我见过的最常见的用例。

因此,如果在代码块中什么也不会发生,pass则需要a 来使该块不产生IndentationError。或者,可以使用任何语句(仅包括要求值的术语,如Ellipsis文字...或字符串,通常是文档字符串),但要说明的pass是,实际上不应该发生任何事情,不需要实际求值,并且(至少暂时)存储在内存中。

  • 忽略(全部或)某种类型的Exception(例如来自xml):

    try:
        self.version = "Expat %d.%d.%d" % expat.version_info
    except AttributeError:
        pass # unknown
    

    注意:忽略所有类型的加薪,如下面的示例中所示pandas,通常被认为是不好的做法,因为它还会捕获可能应该传递给调用者的异常,例如KeyboardInterruptor SystemExit(或HardwareIsOnFireError– 甚至您如何知道自己不是在定义了特定错误的自定义框上运行,某些调用应用程序可能想知道这些错误?)。

    try:
        os.unlink(filename_larry)
    except:
        pass
    

    替代地,至少except Error:或在这种情况下优选地except OSError:被认为是更好的实践。快速分析我安装的所有python模块后,我发现所有except ...: pass语句中有10%以上会捕获所有异常,因此在python编程中它仍然是常见的模式。

  • 派生不会添加新行为的异常类(例如scipy):

    class CompileError(Exception):
        pass
    

    同样,用作抽象基类的类通常具有显式的空值__init__或子类应该派生的其他方法。(例如pebl

    class _BaseSubmittingController(_BaseController):
        def submit(self, tasks): pass
        def retrieve(self, deferred_results): pass
    
  • 测试该代码可以针对一些测试值正确运行,而无需关心结果(来自mpmath):

    for x, error in MDNewton(mp, f, (1,-2), verbose=0,
                             norm=lambda x: norm(x, inf)):
        pass
    
  • 在类或函数定义中,通常已经有一个文档字符串,作为强制性语句要作为块中唯一的内容执行。在这种情况下,该块可能包含pass 文档字符串之外的其他内容,以便说“这确实是无所事事。”,例如pebl

    class ParsingError(Exception): 
        """Error encountered while parsing an ill-formed datafile."""
        pass
    
  • 在某些情况下,pass用作占位符时说“此方法/类/ if-block / …尚未实现,但这将是执行此操作的地方”,尽管我个人更喜欢该Ellipsis文字...,以便在前面的示例中,请严格区分此内容和故意的“无操作”。(请注意,省略号文字仅在Python 3中才是有效的表达式。
    例如,如果我用粗笔写出一个模型,我可能会写

    def update_agent(agent):
        ... 
    

    其他人可能有的地方

    def update_agent(agent):
        pass
    

    之前

    def time_step(agents):
        for agent in agents:
            update_agent(agent)
    

    提醒您update_agent稍后再填写该功能,但已经运行了一些测试以查看其余代码是否按预期运行。(这种情况的第三个选项是raise NotImplementedError。这在两种情况下特别有用:“每个子类都应实现此抽象方法,在此基类中没有定义它的通用方法”,或“此函数具有此名称尚未在此版本中实现,但这是其签名将显示为的样子”

Python has the syntactical requirement that code blocks (after if, except, def, class etc.) cannot be empty. Empty code blocks are however useful in a variety of different contexts, such as in examples below, which are the most frequent use cases I have seen.

Therefore, if nothing is supposed to happen in a code block, a pass is needed for such a block to not produce an IndentationError. Alternatively, any statement (including just a term to be evaluated, like the Ellipsis literal ... or a string, most often a docstring) can be used, but the pass makes clear that indeed nothing is supposed to happen, and does not need to be actually evaluated and (at least temporarily) stored in memory.

  • 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, there is no 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”)


回答 2

除了将其用作未实现函数的占位符外,它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而不是分配,但是在需要突变的情况下,这种方法效果最佳。

使用passhere对警告将来的维护者(包括您自己!)不要在条件语句之外放置多余的步骤特别有用。在上面的示例中,flag在两个具体提到的情况下设置了,但在else-case中没有设置。如果不使用pass,将来的程序员可能会转移flag = True到该条件之外,因此flag所有情况下都应如此。


另一种情况是通常在文件底部看到样板函数:

if __name__ == "__main__":
    pass

在某些文件中,最好保留其中的内容pass,以便以后进行更轻松的编辑,并明确表明在单独运行文件时不会发生任何事情。


最后,如其他答案中所述,捕获异常时不执行任何操作可能很有用:

try:
    n[i] = 0
except IndexError:
    pass

Besides its use as a placeholder for unimplemented functions, pass can be useful in filling out an if-else statement (“Explicit is better than implicit.”)

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

Of course, in this case, one would probably use return instead of assignment, but in cases where mutation is desired, this works best.

The use of pass here is especially useful to warn future maintainers (including yourself!) not to put redundant steps outside of the conditional statements. In the example above, flag is set in the two specifically mentioned cases, but not in the else-case. Without using pass, a future programmer might move flag = True to outside the condition—thus setting flag in all cases.


Another case is with the boilerplate function often seen at the bottom of a file:

if __name__ == "__main__":
    pass

In some files, it might be nice to leave that there with pass to allow for easier editing later, and to make explicit that nothing is expected to happen when the file is run on its own.


Finally, as mentioned in other answers, it can be useful to do nothing when an exception is caught:

try:
    n[i] = 0
except IndexError:
    pass

回答 3

最好和最准确的思考pass方式是明确告诉解释器不执行任何操作的方式。以同样的方式执行以下代码:

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

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

def bar():
    pass

表示“如果我调用函数bar(),则绝对不执行任何操作。”

其他答案非常正确,但是对于一些不涉及占位的事情也很有用。

例如,在我最近使用的一些代码中,有必要将两个变量相除,并且除数可能为零。

c = a / b

如果b为零,显然会产生ZeroDivisionError。在这种特殊情况下,在b为零的情况下,将c保留为零是理想的行为,因此我使用以下代码:

try:
    c = a / b
except ZeroDivisionError:
    pass

另一个较少使用的标准用法是为调试器放置断点的方便位置。例如,我想在for … in语句的第20次迭代中将一些代码插入调试器。所以:

for t in range(25):
    do_a_thing(t)
    if t == 20:
        pass

断点通过。

The best and most accurate way to think of pass is as a way to explicitly tell the interpreter to do nothing. In the same way the following code:

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

means “if I call the function foo(x, y), sum the two numbers the labels x and y represent and hand back the result”,

def bar():
    pass

means “If I call the function bar(), do absolutely nothing.”

The other answers are quite correct, but it’s also useful for a few things that don’t involve place-holding.

For example, in a bit of code I worked on just recently, it was necessary to divide two variables, and it was possible for the divisor to be zero.

c = a / b

will, obviously, produce a ZeroDivisionError if b is zero. In this particular situation, leaving c as zero was the desired behavior in the case that b was zero, so I used the following code:

try:
    c = a / b
except ZeroDivisionError:
    pass

Another, less standard usage is as a handy place to put a breakpoint for your debugger. For example, I wanted a bit of code to break into the debugger on the 20th iteration of a for… in statement. So:

for t in range(25):
    do_a_thing(t)
    if t == 20:
        pass

with the breakpoint on pass.


回答 4

可以“按原样”使用的常见用例是重写类,仅是为了创建类型(否则与超类相同),例如

class Error(Exception):
    pass

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

A common use case where it can be used ‘as is’ is to override a class just to create a type (which is otherwise the same as the superclass), e.g.

class Error(Exception):
    pass

So you can raise and catch Error exceptions. What matters here is the type of exception, rather than the content.


回答 5

pass在Python中基本上不执行任何操作,但是与注释不同,解释器不会忽略它。因此,可以通过将其设置为占位符来在很多地方利用它:

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): # programmer wants to implement the body of the function later
       pass

pass通常在程序员不愿提供实现但仍希望创建某个类/函数/条件语句(以后可以使用)时使用。由于Python解释器不允许空白或未实现的类/函数/条件语句,因此会产生错误:

IndentationError:应缩进的块

pass 可以在这种情况下使用。

pass in Python basically does nothing, but unlike a comment it is not ignored by interpreter. So you can take advantage of it in a lot of places by making it a place holder:

1: Can be used in class

   class TestClass: 
      pass

2: Can be use in loop and conditional statements:

   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: Can be used in function :

   def testFunction(args): # programmer wants to implement the body of the function later
       pass

pass is mostly used when programmer does not want to give implementation at the moment but still wants to create a certain class/function/conditional statement which can be used later on. Since the Python interpreter does not allow for blank or unimplemented class/function/conditional statement it gives an error:

IndentationError: expected an indented block

pass can be used in such scenarios.


回答 6

可以说,通过表示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 "

现在,我认为这很清楚。

You can say that pass means NOP (No Operation) operation. You will get a clear picture after this example :-

C Program

#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 ");
    }
}

Now how you will write that in 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 "

But your code will give error because it required an indented block after elif . Here is the role of pass keyword.

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 "

Now I think its clear to you.


回答 7

我喜欢在进行测试时使用它。我经常知道自己想测试什么,但不太了解该怎么做。测试示例看起来像sebastian_oe所建议的

class TestFunctions(unittest.TestCase):

   def test_some_feature(self):
      pass

   def test_some_other_feature(self):
      pass

I like to use it when stubbing out tests. I often times am aware of what i would like to test but don’t quite know how to do it. Testing example looks like what sebastian_oe suggested

class TestFunctions(unittest.TestCase):

   def test_some_feature(self):
      pass

   def test_some_other_feature(self):
      pass

回答 8

pass语句不执行任何操作。当在语法上需要一条语句但该程序不需要任何操作时,可以使用它。

The pass statement does nothing. It can be used when a statement is required syntactically but the program requires no action.


回答 9

老实说,我认为Python官方文档对此进行了很好的描述并提供了一些示例:

语句什么也不做。当在语法上需要一条语句但该程序不需要任何操作时,可以使用它。例如:

>>> while True: ... pass # Busy-wait for keyboard interrupt (Ctrl+C) ...

这通常用于创建最少的类:

>>> class MyEmptyClass: ... pass ...

当您在处理新代码时,可以使用另一个地方通行证作为函数或条件主体的占位符,从而使您可以继续进行更抽象的思考。该被自动忽略:

>>> def initlog(*args): ... pass # Remember to implement this! ...

Honestly, I think the official Python docs describe it quite well and provide some examples:

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! ...


回答 10

如书中所述,我只曾将其用作临时占位符,即

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

然后填写场景 var == 2000

as the book said, I only ever use it as a temporary placeholder, ie,

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

and then later fill in the scenario where var == 2000


回答 11

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

For i in range (1,100):
    If i%2==0:
                  Pass 
    Else:
                  Print(i)

输出:打印1-100中的所有奇数

这是因为偶数的模数等于零,因此它忽略该数并继续到下一个数字,因为奇数模数不等于零,则执行循环的其他部分并将其打印出来

Pass refers to ignore….as simple as it is ….if the given condition is true and the next statement is pass it ignores that value or iteration and proceed to the next line ….. Example

For i in range (1,100):
    If i%2==0:
                  Pass 
    Else:
                  Print(i)

Output: Prints all the odd numbers from 1-100

This is because modulus of even number is equal to zero ,hence it ignores the number and proceeds to next number ,since odd numbers modulus is not equal to zero the Else part of the loop is executed and its printed


回答 12

这是一个示例,其中我从具有多种数据类型的列表中提取特定数据(这就是我在R中所称的名称,如果命名错误,对不起),我只想提取整数/数字和非字符数据。

数据如下:

>>> a = ['1', 'env', '2', 'gag', '1.234', 'nef']
>>> data = []
>>> type(a)
<class 'list'>
>>> type(a[1])
<class 'str'>
>>> type(a[0])
<class 'str'>

我想删除所有字母字符,所以我让机器通过设置数据子集并“传递”字母数据来做到这一点:

a = ['1', 'env', '2', 'gag', '1.234', 'nef']
data = []
for i in range(0, len(a)):
    if a[i].isalpha():
        pass
    else:
        data.append(a[i])
print(data)
['1', '2', '1.234']

Here’s an example where I was extracting particular data from a list where I had multiple data types (that’s what I’d call it in R– sorry if it’s the wrong nomenclature) and I wanted to extract only integers/numeric and NOT character data.

The data looked like:

>>> a = ['1', 'env', '2', 'gag', '1.234', 'nef']
>>> data = []
>>> type(a)
<class 'list'>
>>> type(a[1])
<class 'str'>
>>> type(a[0])
<class 'str'>

I wanted to remove all alphabetical characters, so I had the machine do it by subsetting the data, and “passing” over the alphabetical data:

a = ['1', 'env', '2', 'gag', '1.234', 'nef']
data = []
for i in range(0, len(a)):
    if a[i].isalpha():
        pass
    else:
        data.append(a[i])
print(data)
['1', '2', '1.234']

回答 13

在语法上需要语句但您不希望执行任何命令或代码时,使用Python中的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语句一起保留,以免干扰代码的其他部分。

The pass statement in Python is used when a statement is required syntactically but you do not want any command or code to execute.

The pass statement is a null operation; nothing happens when it executes. The pass is also useful in places where your code will eventually go, but has not been written yet (e.g., in stubs for example):

`Example:

#!/usr/bin/python

for letter in 'Python': 
   if letter == 'h':
      pass
      print 'This is pass block'
   print 'Current Letter :', letter

print "Good bye!"

This will produce following result:

Current Letter : P
Current Letter : y
Current Letter : t
This is pass block
Current Letter : h
Current Letter : o
Current Letter : n
Good bye!

The preceding code does not execute any statement or code if the value of letter is ‘h’. The pass statement is helpful when you have created a code block but it is no longer required.

You can then remove the statements inside the block but let the block remain with a pass statement so that it doesn’t interfere with other parts of the code.


回答 14

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

pass is used to avoid indentation error in python If we take languages like c,c++,java they have braces like

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

But in python it used indentation instead of braces so to avoid such errors we use pass. Remembered as you were playing a quiz and

 if(dont_know_the_answer)
      pass

Example program,

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