简体   繁体   中英

What is the difference between Pass and None in Python

I would personally like to know the semantic difference between using Pass and None. I could not able to find any difference in execution.

PS: I could not able to find any similar questions in SO. If you find one, please point it out.

Thanks!

pass is a statement . As such it can be used everywhere a statement can be used to do nothing.

None is an atom and as such an expression in its simplest form. It is also a keyword and a constant value for “nothing” (the only instance of the NoneType ). Since it is an expression, it is valid in every place an expression is expected.

Usually, pass is used to signify an empty function body as in the following example:

def foo():
    pass

This function does nothing since its only statement is the no-operation statement pass .

Since an expression is also a valid function body, you could also write this using None :

def foo():
    None

While the function will behave identically, it is a bit different since the expression (while constant) will still be evaluated (although immediately discarded).

In simple terms, None is a value that you can assign to a variable that signifies emptiness. It can be useful as a default state:

a = None
def f():
   a = 5
f()

pass is a statement that is like a nop. It can be useful when you are defining function stubs, for instance:

def f():
    pass

In C-like languages, you would be able to define empty functions by simply putting nothing between the braces void f() { } , but since Python uses indentation instead of braces to define blocks, you must put something in the body, and pass is the idiomatic thing to put there.

That's absolute difference between pass and None

The pass (without upper case P) :

Because python be the indent base language, so if you define a new method, you should have some code after that.

def method_a():
    some_thing = 1  # Have to do some thing

If not, an exception should be raised so you could use the pass keyword for hacks this problem.

def method_a():
    pass  # Do nothing

The None :

So very different, the None keyword has a little bit same to the null keywords from another language like Java or C. That may be the empty data or not assign data like that.

[] == None
null == None
() == None
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM