本文翻译自:return, return None, and no return at all?

Consider three functions: 考虑三个功能:

def my_func1():print "Hello World"return Nonedef my_func2():print "Hello World"returndef my_func3():print "Hello World"

They all appear to return None. 它们似乎都返回None。 Are there any differences between how the returned value of these functions behave? 这些函数的返回值的行为方式之间有什么区别吗? Are there any reasons to prefer one versus the other? 是否有任何理由偏爱一个?


#1楼

参考:https://stackoom.com/question/12CN4/返回-返回无-根本没有返回


#2楼

They each return the same singleton None -- There is no functional difference. 它们每个都返回相同的单例None在功能上没有区别。

I think that it is reasonably idiomatic to leave off the return statement unless you need it to break out of the function early (in which case a bare return is more common), or return something other than None . 我认为离开return语句是合理的习惯做法,除非您需要它早点退出该函数(在这种情况下,裸return比较常见),或者返回None以外的东西。 It also makes sense and seems to be idiomatic to write return None when it is in a function that has another path that returns something other than None . 这也很有意义,并且在函数中具有返回除None其他值的函数时,写return None似乎是惯用的。 Writing return None out 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 None明确写出是读者的视觉提示,因为还有另一个分支返回了更有趣的内容(并且调用代码可能需要处理两种类型的返回值)。

Often in Python, functions which return None are used like void functions in C -- Their purpose is generally to operate on the input arguments in place (unless you're using global data ( shudders )). 在Python中,返回None的函数通常与C中的void函数一起使用-它们的目的通常是对输入参数进行适当的操作 (除非您使用全局数据( shudders ))。 Returning None usually makes it more explicit that the arguments were mutated. 返回None通常可以使参数更明确地变得更明确。 This makes it a little more clear why it makes sense to leave off the return statement from a "language conventions" standpoint. 这使我们更加清楚为什么从“语言约定”的角度出发,放弃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... 就是说,如果您正在使用已经针对这些事情设置了预设约定的代码库,那么我肯定会效仿以帮助使代码库保持一致...


#3楼

On the actual behavior, there is no difference. 在实际行为上,没有区别。 They all return None and that's it. 他们都返回None ,仅此而已。 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. 以下说明基本上是应如何使用不同方法的方法(或至少应告诉我如何使用它们的方法),但是它们不是绝对规则,因此您可以根据需要将它们混合使用。

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 . 这说明该函数确实是要返回一个值供以后使用,在这种情况下,它返回None This value None can then be used elsewhere. 此值None可以在其他地方使用。 return None is never used if there are no other possible return values from the function. 如果该函数没有其他可能的返回值,则从不使用return None

In the following example, we return person 's mother if the person given is a human. 在以下示例中,如果给定的person是人类,我们将返回personmother If it's not a human, we return None since the person doesn't have a mother (let's suppose it's not an animal or something). 如果不是人,则由于该person没有mother (因此假设它不是动物或其他东西),我们将返回None

def get_mother(person):if is_human(person):return person.motherelse:return None

Using return 使用return

This is used for the same reason as break in loops. 出于与break循环相同的原因使用它。 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. 即使您不经常使用它,它在某些地方也非常有用。

We've got 15 prisoners and we know one of them has a knife. 我们有15 prisoners ,我们知道其中一个有一把刀。 We loop through each prisoner one by one to check if they have a knife. 我们逐个循环检查每个prisoner ,以检查他们是否有刀。 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 . 如果我们用刀子打人,我们就可以退出该功能,因为我们知道只有一把刀子,没有理由检查其余prisoners If we don't find the prisoner with a knife, we raise an alert. 如果我们没有用刀找到prisoner ,我们会发出警报。 This could be done in many different ways and using return is probably not even the best way, but it's just an example to show how to use return for exiting a function. 这可以通过许多不同的方式完成,使用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 alertraise_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 return at all 根本没有return

This will also return None , but that value is not meant to be used or caught. 这也将返回None ,但是该值并不意味着要使用或捕获。 It simply means that the function ended successfully. 这仅表示该功能已成功结束。 It's basically the same as return in void functions in languages such as C++ or Java. 它基本上与以C ++或Java这样的语言在void函数中return相同。

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) ,因为这并不意味着要捕获返回值。


#4楼

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 disdef f1():print "Hello World"return Nonedef f2():print "Hello World"returndef f3():print "Hello World"dis.dis(f1)4   0 LOAD_CONST    1 ('Hello World')3 PRINT_ITEM4 PRINT_NEWLINE5   5 LOAD_CONST    0 (None)8 RETURN_VALUEdis.dis(f2)9   0 LOAD_CONST    1 ('Hello World')3 PRINT_ITEM4 PRINT_NEWLINE10  5 LOAD_CONST    0 (None)8 RETURN_VALUEdis.dis(f3)14  0 LOAD_CONST    1 ('Hello World')3 PRINT_ITEM4 PRINT_NEWLINE            5 LOAD_CONST    0 (None)8 RETURN_VALUE

#5楼

就功能而言,它们都是相同的,它们之间的区别在于代码的可读性和样式(要考虑的重要因素)

返回,返回无,根本没有返回?相关推荐

  1. java无参_Java中无参无返回和无参带返回的类型方法

    在前面的文章中,我们学习了java中方法的定义.分类及调用的相关知识.知道了java中的方法其实可以叫做函数,目的是实现某些我们想要的功能,也知道了java中方法的分类共有四种:无参无返回.无参带返回 ...

  2. java学习(46):无参带返回

    /*1. 如果方法的返回类型为 void ,则方法中不能使用 return 返回值! *2. 方法的返回值最多只能有一个,不能返回多个值 *3. 方法返回值的类型必须兼容,例如,如果返回值类型为 in ...

  3. oracle java存储过程返回值_java程序调用Oracle 存储过程 获取返回值(无返回,非结果集,结果集)...

    java程序调用Oracle 存储过程 获取返回值(无返回,非结 果集,结果集) oracle中procedure是不能有返回值的,要想返回值,就得有 输出参数,同样要想返回记录集,可以把游标类型作为 ...

  4. layui fixbar 返回顶部_FANUC 数控系统机床返回参考点功能的应用研究

    摘要:数控机床能精确控制零件的加工精度,而它的加工是要基于一个固定的参考点,而参考点的位置就是以机床出厂零点为基准的.通过研究使用 FANUC 数控系统的数控机床建立参考点的方式,研究返回参考点的三种 ...

  5. java 全局返回码设计_服务返回码的设计

    服务返回码的设计 服务的返回码指示服务正常返回结果或是执行出现异常. 最简单的设计 返回码只有两个:成功,服务正常返回:失败,服务执行出现异常. 实际情况下,返回码只有成功和失败可能不能满足需求. 程 ...

  6. (转)C#进阶系列——WebApi 接口返回值不困惑:返回值类型详解

    原文链接:https://www.cnblogs.com/landeanfen/p/5501487.html 阅读目录 一.void无返回值 二.IHttpActionResult 1.Json(T ...

  7. 接口返回html转换josn,接口返回数据Json格式处理

    有这样一个页面 , 用来显示用户的账户记录数据,并且需要显示每个月的 收入 支出合计 ,在分页的时候涉及到一些问题,需要对返回的Json格式做处理,处理起来比较麻烦,后端返回的Json数据格式形式如下 ...

  8. b站pink老师JavaScript的PC端网页特效 案例代码——仿淘宝返回顶部(带有动画的返回顶部)

    目标效果: 在之前写好的 的代码基础上 实现点击返回顶部字样,即可用缓动动画返回顶部[见代码段中4.和动画函数部分] 重点语法: 滚动窗口至文档中的特定位置 window.scroll(x,y) x, ...

  9. pandas使用groupby函数和count函数返回的是分组下每一列的统计值(不统计NaN缺失值)、如果多于一列返回dataframe、size函数返回分组下的行数结果为Series(缺失值不敏感)

    pandas使用groupby函数和count函数返回的是分组下每一列的统计值(不统计NaN缺失值).如果多于一列返回dataframe.size函数返回分组下的行数结果为Series(不区分缺失值和 ...

  10. build_transformer_model如果不返回keras的bert模型返回的是什么?

    build_transformer_model 还有两个问题: 1.如果不返回keras的bert模型返回的是什么? bert = build_transformer_model( config_pa ...

最新文章

  1. 李宏毅机器学习笔记(三)——Regression: output a scalar amp;amp; Gradient Descent
  2. 被马斯克送上天的《银河帝国》和互联网江湖 | 赠书
  3. KaliLinux常用服务配置教程DHCP服务工作流程
  4. https下 http的会被阻塞 This request has been blocked; the content must be served over HTTPS.
  5. EditText 自动保留两位小数
  6. spark集群测试小案例
  7. 通道Channel-使用NIO 写入数据
  8. TensorFlow | ReluGrad input is not finite. Tensor had NaN values
  9. 基于单片机USB接口的温度控制器
  10. LaTeX目录格式控制
  11. 上海计算机应用基础自考上机,2012年上海自考《计算机应用基础》上机考核大纲...
  12. 初中数学课程与信息技术的整合
  13. 阿里技术专家:从程序员到技术总监,我的十五年IT路!
  14. ruby语言学习-开启篇
  15. 深圳南山区学位申请特殊住房需要的材料有哪些
  16. 数分笔记整理25 - 数据处理项目 - 中国城市资本流动问题探索
  17. ServerSocket通过构造方法绑定端口
  18. (Verilog)多周期CPU设计
  19. TensorFlow 网络模型移植和训练指南
  20. 基于BP神经网络的车牌识别系统的设计

热门文章

  1. 清空SQL Server数据库日志的SQL语句
  2. android sqlite 自增长序列号归0
  3. 算法---------括号生成
  4. Abp mysql guid_.NET生成多数据库有序Guid
  5. diskgeniusv4.4.0_.NET Core 3.0及ASP.NET Core 3.0前瞻
  6. 第一阶段团队成员贡献打分
  7. Linux 系统必须掌握的文件_【all】
  8. Android初学第29天
  9. MYSQL之SQL语句练习及思路_1
  10. 剑指offer 把数组排成最小的数 atoi和itoa,pow