繁体   English   中英

为什么函数在python中以“return 0”而不是“return”结尾?

[英]Why would a function end with “return 0” instead of “return” in python?

你能解释一下“回归0”和“回归”之间的区别吗? 例如:

do_1():
    for i in xrange(5):
        do_sth()
    return 0

do_2():
    for i in xrange(5):
        do_sth()
    return 

上面两个函数有什么区别?

取决于用法:

>>> def ret_Nothing():
...     return
... 
>>> def ret_None():
...     return None
... 
>>> def ret_0():
...     return 0
... 
>>> ret_Nothing() == None
True
>>> ret_Nothing() is None  # correct way to compare values with None
True
>>> ret_None() is None
True
>>> ret_0() is None
False
>>> ret_0() == 0
True
>>> # and...
>>> repr(ret_Nothing())
'None'

Tichodroma所述0不等于None 但是,在布尔上下文中 ,它们都是False

>>> if ret_0():
...     print 'this will not be printed'
... else:
...     print '0 is boolean False'
... 
0 is boolean False
>>> if ret_None():
...     print 'this will not be printed'
... else:
...     print 'None is also boolean False'
... 
None is also boolean False

有关Python中布尔上下文的更多信息: 真值测试

def do_1():
    return 0

def do_2():
    return

# This is the difference
do_1 == 0 # => True
do_2 == 0 # => False

在python中,函数将显式或隐式返回None

例如

# Explicit
def get_user(id):
    user = None
    try:
        user = get_user_from_some_rdbms_byId(id)
    except:
        # Our RDBMS raised an exception because the ID was not found.
        pass
    return user  # If it is None, the caller knows the id was not found.

# Implicit
def add_user_to_list(user):
    user_list.append(user)   # We don't return something, so implicitly we return None

由于某些计算,python函数将返回0

def add_2_numbers(a,b):
    return a + b      # 1 -1 would return 0

或者因为magic旗的那种东西,这是不赞成的。

但是在python中我们不使用0来表示成功,因为:

if get_user(id):

如果我们返回0则不会评估为True因此if分支不会运行。

In [2]: bool(0)
Out[2]: False

它与python无关。

每当执行一个函数时,您都可以选择返回一个值。

return关键字是告诉函数它是否应该返回值的内容。

如果没有给return值,或者没有赋值返回,则返回值为None

如果指定一个值,在这种情况下,返回0 ,那么函数将返回值0 ,并且当达到return关键字和值时,函数将结束。

在一些更多的信息0 :一个理由0将使用是因为它是普遍,它会返回函数0是“成功”和非零返回值不是简单地要返回的值,或有时错误代码,如果函数做没有正确执行。

在Python中, 每个函数都隐式或显式地返回一个返回值。

>>> def foo():
...     x = 42
... 
>>> def bar():
...     return
... 
>>> def qux():
...     return None
... 
>>> def zero():
...     return 0
... 
>>> print foo()
None
>>> print bar()
None
>>> print qux()
None
>>> print zero()
0

如您所见, foobarqux返回完全相同,内置常量None

  • foo返回None因为缺少return语句,如果函数没有显式返回值,则None是缺省返回值。

  • bar返回None因为它使用不带参数的return语句,默认为None

  • qux返回None因为它明确地这样做。

然而, zero完全不同并返回整数0

如果评估为布尔值 ,则0None都评估为False ,但除此之外,它们非常不同(事实上,不同的类型, NoneTypeint )。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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