Python 如何使用pass语句?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13886168/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use the pass statement?
提问by Capurnicus
I am in the process of learning Python and I have reached the section about the passstatement. The guide I'm using defines it as being a Nullstatement that is commonly used as a placeholder.
我正在学习 Python,我已经到了关于pass语句的部分。我使用的指南将其定义Null为通常用作占位符的语句。
I still don't fully understand what that means though. Can someone show me a simple/basic situation where the passstatement would be used and why it is needed?
我仍然不完全明白这意味着什么。有人可以向我展示一个简单/基本的情况,其中pass将使用该语句以及为什么需要它?
采纳答案by sebastian_oe
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.
如果您省略pass,代码将不会运行。
You would then get an:
然后你会得到一个:
IndentationError: expected an indented block
To summarize, the passstatement does nothing particular, but it can act as a placeholder, as demonstrated here.
总而言之,该pass语句没有什么特别之处,但它可以充当占位符,如此处所示。
回答by dm03514
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
我喜欢在剔除测试时使用它。我经常知道我想测试什么,但不太知道如何去做。测试示例看起来像 sebastian_oe 建议的那样
class TestFunctions(unittest.TestCase):
def test_some_feature(self):
pass
def test_some_other_feature(self):
pass
回答by Cameron Sparr
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
然后填写场景 var == 2000
回答by Cameron Sparr
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 Errorexceptions. What matters here is the type of exception, rather than the content.
因此,您可以引发和捕获Error异常。这里重要的是异常的类型,而不是内容。
回答by Micah Walter
Besides its use as a placeholder for unimplemented functions, passcan be useful in filling out an if-else statement ("Explicit is better than implicit.")
除了用作未实现函数的占位符外,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
Of course, in this case, one would probably use returninstead of assignment, but in cases where mutation is desired, this works best.
当然,在这种情况下,人们可能会使用return而不是赋值,但在需要突变的情况下,这最有效。
The use of passhere is especially useful to warn future maintainers (including yourself!) not to put redundant steps outside of the conditional statements. In the example above, flagis set in the two specifically mentioned cases, but not in the else-case. Without using pass, a future programmer might move flag = Trueto outside the condition—thus setting flagin allcases.
pass这里的使用特别有用,可以警告未来的维护者(包括你自己!)不要在条件语句之外放置多余的步骤。在上面的例子中,flag是在两个特别提到的情况下设置的,但不是在 -else情况下。如果不使用pass,未来的程序员可能会移动flag = True到条件之外——因此flag在所有情况下都设置。
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 passto allow for easier editing later, and to make explicit that nothing is expected to happen when the file is run on its own.
在某些文件中,最好将其保留在那里pass以便以后更轻松地进行编辑,并明确表示当文件单独运行时不会发生任何事情。
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
回答by Schilcote
The best and most accurate way to think of passis as a way to explicitly tell the interpreter to do nothing. In the same way the following code:
最好和最准确的思考pass方式是明确告诉解释器什么都不做。以同样的方式编写以下代码:
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",
意思是“如果我调用函数 foo(x, y),将标签 x 和 y 表示的两个数字相加并返回结果”,
def bar():
pass
means "If I call the function bar(), do absolutely nothing."
意思是“如果我调用函数 bar(),什么都不做。”
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:
显然,如果 b 为零,则会产生 ZeroDivisionError。在这种特殊情况下,在 b 为零的情况下,将 c 保留为零是所需的行为,因此我使用了以下代码:
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... in 语句的第 20 次迭代中进入调试器。所以:
for t in range(25):
do_a_thing(t)
if t == 20:
pass
with the breakpoint on pass.
通过断点。
回答by Anaphory
Python has the syntactical requirement that code blocks (after if, except, def, classetc.) 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.
Python有句法的要求,即代码块(后if,except,def,class等等)不能为空。然而,空代码块在各种不同的上下文中都很有用,例如在下面的示例中,这是我见过的最常见的用例。
Therefore, if nothing is supposed to happen in a code block, a passis needed for such a block to not produce an IndentationError. Alternatively, any statement (including just a term to be evaluated, like the Ellipsisliteral ...or a string, most often a docstring) can be used, but the passmakes clear that indeed nothing is supposed to happen, and does not need to be actually evaluated and (at least temporarily) stored in memory.
因此,如果代码块中不应该发生任何事情,pass则需要 a 使这样的块不产生IndentationError. 或者,可以使用任何语句(仅包括要评估的术语,如Ellipsis文字...或字符串,最常见的是文档字符串),但pass明确表示确实不应该发生任何事情,并且不需要实际评估和(至少暂时)存储在内存中。
Ignoring (all or) a certain type of
Exception(example fromxml):try: self.version = "Expat %d.%d.%d" % expat.version_info except AttributeError: pass # unknownNote: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.KeyboardInterruptorSystemExit(or evenHardwareIsOnFireError– 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: passInstead using at least
except Error:or in this case preferablyexcept OSError:is considered much better practice. A quick analysis of all python modules I have installed gave me that more than 10% of allexcept ...: passstatements 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): passSimilarly, 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): passTesting 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)): passIn class or function definitions, often a docstring is already in place as the obligatory statementto be executed as the only thing in the block. In such cases, the block may contain
passin additionto the docstring in order to say “This is indeed intended to do nothing.”, for example inpebl:class ParsingError(Exception): """Error encountered while parsing an ill-formed datafile.""" passIn some cases,
passis 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 theEllipsisliteral...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 writedef update_agent(agent): ...where others might have
def update_agent(agent): passbefore
def time_step(agents): for agent in agents: update_agent(agent)as a reminder to fill in the
update_agentfunction 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 israise 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”)
忽略(全部或)某种类型的
Exception(例如来自xml):try: self.version = "Expat %d.%d.%d" % expat.version_info except AttributeError: pass # unknown注意:忽略所有类型的加薪,如以下来自 的示例
pandas,通常被认为是不好的做法,因为它还会捕获可能应该传递给调用者的异常,例如KeyboardInterrupt或SystemExit(或什HardwareIsOnFireError至 - 你怎么知道你不是在定义了特定错误的自定义框上运行,某些调用应用程序会想知道哪些错误?)。try: os.unlink(filename_larry) except: pass相反,至少使用
except Error:或在这种情况下最好except OSError:被认为是更好的做法。对我安装的所有 python 模块的快速分析告诉我,超过 10% 的except ...: pass语句捕获所有异常,因此它仍然是 python 编程中的常见模式。派生一个不添加新行为的异常类(例如 in
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。这对两种情况特别有用:“这个抽象方法应该由每个子类实现,没有通用的方法在这个基类中定义它”,或者“这个函数,具有此名称尚未在此版本中实现,但这就是其签名的样子”)
回答by Harsha Biyani
The pass statement does nothing. It can be used when a statement is required syntactically but the program requires no action.
pass 语句什么都不做。它可以在语法上需要语句但程序不需要操作时使用。
回答by Edward Tyler
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.
这是一个示例,我从具有多种数据类型的列表中提取特定数据(这就是我在 R 中的称呼——抱歉,如果命名法有误),我只想提取整数/数字而不是字符数据.
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']
回答by Arijit
passin 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:
pass在 Python 中基本上什么都不做,但与注释不同的是,它不会被解释器忽略。因此,您可以通过将其设置为占位符来在很多地方利用它:
1: Can be used in class
1:可以在课堂上使用
class TestClass:
pass
2: Can be use in loop and conditional statements:
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: Can be used in function :
3:可用于功能:
def testFunction(args): # programmer wants to implement the body of the function later
pass
passis 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:
pass主要用于程序员目前不想给出实现但仍想创建某个类/函数/条件语句以便以后使用的情况。由于 Python 解释器不允许使用空白或未实现的类/函数/条件语句,因此会出现错误:
IndentationError: expected an indented block
IndentationError:需要一个缩进块
passcan be used in such scenarios.
pass可用于此类场景。

