我在学习Python的过程中,我已经到了关于pass语句的部分。我正在使用的指南将其定义为通常用作占位符的空语句。
但我还是不太明白这是什么意思。pass语句将被使用的简单/基本情况是什么?为什么需要它?
我在学习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语句不做任何特殊的事情,但它可以充当占位符,如下所示。
其他回答
假设您正在设计一个新类,其中包含一些您还不想实现的方法。
class MyClass(object):
def meth_a(self):
pass
def meth_b(self):
print "I'm meth_b"
如果您省略了传递,代码将无法运行。
然后你会得到一个:
IndentationError: expected an indented block
总之,pass语句不做任何特殊的事情,但它可以充当占位符,如下所示。
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 !!
谢谢!
正如书中所说,我只把它用作临时占位符,也就是说,
# code that does something to to a variable, var
if var == 2000:
pass
else:
var += 1
然后填充var == 2000的场景。
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
老实说,我认为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! ...