关于python的return用法,在stackoverflow里的问题:

Python — return, return None, and no return at all

Consider three functions:

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

On the actual behavior, there is no difference. They all return None and 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.

Using 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 None can then be used elsewhere. return None is never used if there are no other possible return values from the function.

In the following example, we return person's mother if the person given is a human. 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 so).

def get_mother(person):
if is_human(person):
return person.mother
else:
return None

Note: You should never do var = get_mother(), since let us assume var is a dictionary and you iterate by var.items() it will give an error citing None has no method items(). It you intentionally return None then it must be taken care of in the calling function appropriately.

Using return

This is used for the same reason as break in loops. The return value doesn't matter and you only want to exit the whole function. It's extremely useful in some places, even tho you don't need it that often.

We got 15 prisoners and we know one of them has a knife. We loop through each prisoner one by one to check if they have a knife. If we hit the person with a knife, we can just exit the function cause we know there's only one knife and no reason the check rest of the prisoners. If we don't find the prisoner with a knife, we raise an the alert. 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.

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.

Using no return at all

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 return in void functions in languages such as C++ or Java.

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.

python的return的更多相关文章

  1. python中 return 的用法

    return 语句就是讲结果返回到调用的地方,并把程序的控制权一起返回 程序运行到所遇到的第一个return即返回(退出def块),不会再运行第二个return. 要返回两个数值,写成一行即可: de ...

  2. Python中return self的用法

      在Python中,有些开源项目中的方法返回结果为self. 对于不熟悉这种用法的读者来说,这无疑使人困扰,本文的目的就是给出这种语法的一个解释,并且给出几个例子.   在Python中,retur ...

  3. python中return和print的区别(详细)

    huskiesir最近在研究python哈,今天纠结一个问题,那就是return和print的区别,都是可以输出结果的,到底有啥区别呀?二话不多说,看下面的例子. #代码1: def break_wo ...

  4. python——比return优先级更高的语句

    调用sqlmap,使用sqlmap做二次开发的时候,出现的问题: 在调用sqlmap中return,然而主程序还是会被sqlmap中的某些代码给中断. 添加try也无法阻止中断. 后来猜测中断是由ex ...

  5. python的return self的用法

    转载:https://blog.csdn.net/jclian91/article/details/81238782 class foo: def __init__(self): self.m = 0 ...

  6. [Python]关于return逻辑判断和短路逻辑

    定义一个return...and..函数: def res(): ' 返回结果: >>> print(res()) 1234 定义一个return...or..函数: def res ...

  7. python中return的用法

    def testReturn(x): if x > 10000: return print "test return!!" #这句话永远不会得到执行 elif x > ...

  8. Python的return self和return一个新的对象区别

    目的:设计一个有理数相加.如3/5 + 7/15 = 80/75 return self 输入: class Rational0: def __init__(self, num, den=1): se ...

  9. Python随笔---return与print,全局变量与局部变量

    Return是指返回一个数值,一般在函数中应用较多 Print则是指把结果打印出来,显示在屏幕上 def sum(a,b): total=a+b print('函数内:',total) return ...

随机推荐

  1. Java 的Integer、int与new Integer到底怎么回事?

    先做一些总结,询问了些经验比较多的师傅,在这里表示感谢,然后自己总结下,今天的收获分享给大家: 1. int 和Integer在进行比较的时候,Integer会进行拆箱,转为int值与int进行比较. ...

  2. 【转】Ubuntu12.04安装YouCompleteMe插件

    原文网址:http://m.blog.csdn.net/blog/unhappypeople/19160243 以前用的都是ctags+omnicomplete+acp的方式,这次换成clang自解析 ...

  3. coding github 配置ssl 免密拉取代码

    详细介绍: https://www.cnblogs.com/superGG1990/p/6844952.html 注:其中检验过程与下述不同,可以先在对应git库使用 git pull 一次,选择信任 ...

  4. 【UVA】10891 Game of Sum(区间dp)

    题目 传送门:QWQ 分析 大力dp.用$ dp[i][j] $表示$ [i,j] $A能得到的最高分 我看到博弈论就怂... 代码 #include <bits/stdc++.h> us ...

  5. c#静态构造函数与构造函数

    构造函数这个概念,在我们刚开始学习编程语言的时候,就被老师一遍一遍的教着.亲,现在你还记得静态构造函数的适用场景吗?如果没有,那么我们一起来复习一下吧. 静态构造函数是在构造函数方法前面添加了stat ...

  6. Django之路 - 实现登录随机验证码

    登录验证码是每个网站登录时的基本标配,网上也有很多相应的文章, 但是从生成验证码到 应用到自己的网站上的全步骤,并没有看到很多, 为了节约大家的时间,我把整体步骤写下来, 即拿即用哈 1. 生成随机验 ...

  7. ADO.Net学习总结

    一.讲述6个ADO.NET中的常用对象: Connection对象Command对象DataReader对象DataAdapter对象DataSet对象DataTable对象DataRow对象Data ...

  8. CentOS+Tomcat环境搭建

    此次搭建是基于: CentOS release 5.6 (Final) Kernel \r on an \m 搭建准备:http://pan.baidu.com/s/1pLt1lLh apache-t ...

  9. VsCode中vim插件剪切板等问题

    剪切板共享 这个挺重要的,否则每次右键菜单复制粘贴会奔溃的. 在用户设置中添加: "vim.useSystemClipboard": true, 光标的变化 我觉得这个也重要,毕竟 ...

  10. filebeat 笔记

    认识Beats Beats是用于单用途数据托运人的平台.它们以轻量级代理的形式安装,并将来自成百上千台机器的数据发送到Logstash或Elasticsearch. (画外音:通俗地理解,就是采集数据 ...