我在学习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语句不做任何特殊的事情,但它可以充当占位符,如下所示。

其他回答

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

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

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

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

谢谢!

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”)

假设您正在设计一个新类,其中包含一些您还不想实现的方法。

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

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

如果您省略了传递,代码将无法运行。

然后你会得到一个:

IndentationError: expected an indented block

总之,pass语句不做任何特殊的事情,但它可以充当占位符,如下所示。

除了“我不想要任何东西到这里”的“主要”用途之外,我刚刚发现了一个,假设gen是一个迭代器:

i = 0
obj = None

for i, obj in enumerate(gen):
    pass

这将在一次传递中获得gen生成的最后一个对象和gen的长度。(有点类似于C语言中以分号结尾的while循环,仔细想想吧。)