Python 返回,返回无,根本不返回?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15300550/
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
return, return None, and no return at all?
提问by Clay Wardell
Consider three functions:
考虑三个函数:
def my_func1():
print "Hello World"
return None
def my_func2():
print "Hello World"
return
def my_func3():
print "Hello World"
They all appear to return None. Are there any differences between how the returned value of these functions behave? Are there any reasons to prefer one versus the other?
它们似乎都返回 None。这些函数的返回值的行为方式有什么不同吗?有什么理由更喜欢一种而不是另一种吗?
采纳答案by mgilson
On the actual behavior, there is no difference. They all return Noneand that's it. However, there is a time and place for all of these.
The following instructions are basically how the different methods should be used (or at least how I was taught they should be used), but they are not absolute rules so you can mix them up if you feel necessary to.
在实际行为上,没有区别。他们都回来了None,就是这样。然而,所有这些都有一个时间和地点。下面的说明基本上是应该如何使用不同的方法(或者至少我被教导应该如何使用它们),但它们不是绝对的规则,因此如果您觉得有必要,可以将它们混合起来。
Using return None
使用 return None
This tells that the function is indeed meant to return a value for later use, and in this case it returns None. This value Nonecan then be used elsewhere. return Noneis never used if there are no other possible return values from the function.
这表明该函数确实是要返回一个值供以后使用,在这种情况下它返回None. None然后可以在其他地方使用该值。return None如果函数没有其他可能的返回值,则永远不会使用。
In the following example, we return person's motherif the persongiven is a human. If it's not a human, we return Nonesince the persondoesn't have a mother(let's suppose it's not an animal or something).
在下面的示例中,如果给定的是人类,我们将返回person's 。如果它不是人类,我们将返回,因为它没有(假设它不是动物或其他东西)。motherpersonNonepersonmother
def get_mother(person):
if is_human(person):
return person.mother
else:
return None
Using return
使用 return
This is used for the same reason as breakin loops. The return value doesn't matter and you only want to exit the whole function. It's extremely useful in some places, even though you don't need it that often.
这与break在循环中使用的原因相同。返回值无关紧要,您只想退出整个函数。它在某些地方非常有用,即使您并不经常需要它。
We've got 15 prisonersand we know one of them has a knife. We loop through each prisonerone by one to check if they have a knife. If we hit the person with a knife, we can just exit the function because we know there's only one knife and no reason the check rest of the prisoners. If we don't find the prisonerwith a knife, we raise an alert. This could be done in many different ways and using returnis probably not even the best way, but it's just an example to show how to use returnfor exiting a function.
我们有 15 个prisoners,我们知道其中一个有刀。我们prisoner一个一个地循环检查他们是否有刀。如果我们用刀击中了人,我们可以退出函数,因为我们知道只有一把刀并且没有理由检查prisoners. 如果我们没有找到prisoner带刀的人,我们就会发出警报。这可以通过许多不同的方式来完成,使用return可能甚至不是最好的方式,但这只是展示如何使用return退出函数的一个例子。
def find_prisoner_with_knife(prisoners):
for prisoner in prisoners:
if "knife" in prisoner.items:
prisoner.move_to_inquisition()
return # no need to check rest of the prisoners nor raise an alert
raise_alert()
Note: You should never do var = find_prisoner_with_knife(), since the return value is not meant to be caught.
注意:你永远不应该这样做var = find_prisoner_with_knife(),因为返回值并不意味着被捕获。
Using no returnat all
使用无return可言
This will also return None, but that value is not meant to be used or caught. It simply means that the function ended successfully. It's basically the same as returnin voidfunctions in languages such as C++ or Java.
这也将返回None,但该值并不意味着被使用或捕获。它只是意味着该功能已成功结束。它与 C++ 或 Java 等语言return中的void函数基本相同。
In the following example, we set person's mother's name and then the function exits after completing successfully.
在下面的例子中,我们设置了人的母亲的名字,然后函数在成功完成后退出。
def set_mother(person, mother):
if is_human(person):
person.mother = mother
Note: You should never do var = set_mother(my_person, my_mother), since the return value is not meant to be caught.
注意:你永远不应该这样做var = set_mother(my_person, my_mother),因为返回值并不意味着被捕获。
回答by mgilson
They each return the same singleton None-- There is no functional difference.
它们都返回相同的单例None——没有功能差异。
I think that it is reasonably idiomatic to leave off the returnstatement unless you need it to break out of the function early (in which case a bare returnis more common), or return something other than None. It also makes sense and seems to be idiomatic to write return Nonewhen it is in a function that has another path that returns something other than None. Writing return Noneout explicitly is a visual cue to the reader that there's another branch which returns something more interesting (and that calling code will probably need to handle both types of return values).
我认为放弃该return语句是合理惯用的,除非您需要它尽早脱离函数(在这种情况下,barereturn更常见),或者返回None. 这也有道理,似乎是惯用的以写return None时,它是在具有另一个路径的功能比其他东西的回报None。return None明确写出是对读者的视觉提示,即还有另一个分支返回更有趣的东西(并且调用代码可能需要处理这两种类型的返回值)。
Often in Python, functions which return Noneare used like voidfunctions in C -- Their purpose is generally to operate on the input arguments in place(unless you're using global data (shudders)). Returning Noneusually makes it more explicit that the arguments were mutated. This makes it a little more clear why it makes sense to leave off the returnstatement from a "language conventions" standpoint.
通常在 Python 中,返回None的void函数就像C 中的函数一样使用——它们的目的通常是在适当的位置对输入参数进行操作(除非您使用全局数据(颤抖))。返回None通常会使参数发生变异更加明确。这使得更清楚为什么return从“语言约定”的角度离开这个语句是有意义的。
That said, if you're working in a code base that already has pre-set conventions around these things, I'd definitely follow suit to help the code base stay uniform...
也就是说,如果您在一个已经有关于这些事情的预设约定的代码库中工作,我肯定会效仿以帮助代码库保持统一......
回答by David Marx
Yes, they are all the same.
是的,它们都是一样的。
We can review the interpreted machine code to confirm that that they're all doing the exact same thing.
我们可以查看解释的机器代码以确认它们都在做完全相同的事情。
import dis
def f1():
print "Hello World"
return None
def f2():
print "Hello World"
return
def f3():
print "Hello World"
dis.dis(f1)
4 0 LOAD_CONST 1 ('Hello World')
3 PRINT_ITEM
4 PRINT_NEWLINE
5 5 LOAD_CONST 0 (None)
8 RETURN_VALUE
dis.dis(f2)
9 0 LOAD_CONST 1 ('Hello World')
3 PRINT_ITEM
4 PRINT_NEWLINE
10 5 LOAD_CONST 0 (None)
8 RETURN_VALUE
dis.dis(f3)
14 0 LOAD_CONST 1 ('Hello World')
3 PRINT_ITEM
4 PRINT_NEWLINE
5 LOAD_CONST 0 (None)
8 RETURN_VALUE
回答by Yehuda Schwartz
In terms of functionality these are all the same, the difference between them is in code readability and style (which is important to consider)
在功能方面,这些都是相同的,它们之间的区别在于代码可读性和风格(这很重要)
回答by Fabiano
As other have answered, the result is exactly the same, Noneis returned in all cases.
正如其他人回答的那样,结果完全相同,None在所有情况下都返回。
The difference is stylistic, but please note that PEP8requires the use to be consistent:
区别在于文体,但请注意PEP8要求使用保持一致:
Be consistent in return statements. Either all return statements in a function should return an expression, or none of them should. If any return statement returns an expression, any return statements where no value is returned should explicitly state this as return None, and an explicit return statement should be present at the end of the function (if reachable).
Yes:
def foo(x): if x >= 0: return math.sqrt(x) else: return None def bar(x): if x < 0: return None return math.sqrt(x)No:
def foo(x): if x >= 0: return math.sqrt(x) def bar(x): if x < 0: return return math.sqrt(x)
在 return 语句中保持一致。函数中的所有 return 语句都应该返回一个表达式,或者它们都不应该返回。如果任何 return 语句返回一个表达式,则任何没有返回值的 return 语句都应将其明确声明为 return None,并且应在函数的末尾(如果可到达)显示一个明确的 return 语句。
是的:
def foo(x): if x >= 0: return math.sqrt(x) else: return None def bar(x): if x < 0: return None return math.sqrt(x)不:
def foo(x): if x >= 0: return math.sqrt(x) def bar(x): if x < 0: return return math.sqrt(x)
https://www.python.org/dev/peps/pep-0008/#programming-recommendations
https://www.python.org/dev/peps/pep-0008/#programming-recommendations
Basically, if you ever return non-Nonevalue in a function, it means the return value has meaning and is meant to be caught by callers. So when you return None, it must also be explicit, to convey Nonein this case has meaning, it is one of the possible return values.
基本上,如果您曾None在函数中返回非值,则意味着返回值具有意义并且旨在被调用者捕获。所以当你 return 时None,它也必须是明确的,None在这种情况下传达的意思是,它是可能的返回值之一。
If you don't need return at all, you function basically works as a procedure instead of a function, so just don't include the returnstatement.
如果你根本不需要 return,你的函数基本上是作为一个过程而不是一个函数,所以不要包含这个return语句。
If you are writing a procedure-like function and there is an opportunity to return earlier (i.e. you are already done at that point and don't need to execute the remaining of the function) you may use empty an returns to signal for the reader it is just an early finish of execution and the Nonevalue returned implicitly doesn't have any meaning and is not meant to be caught (the procedure-like function always returns Noneanyway).
如果您正在编写一个类似过程的函数并且有机会提前返回(即您已经完成了该点并且不需要执行该函数的其余部分)您可以使用空 an returns 向读者发出信号它只是执行的提早结束,None隐式返回的值没有任何意义并且不打算被捕获(类似过程的函数总是返回None)。

