是否有可能不会返回任何东西在python中的函数? [英] is it possible to not return anything from a function in python?

查看:115
本文介绍了是否有可能不会返回任何东西在python中的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用一个简单的过滤器,测试输入的范围是0-100。

  def foo(foo_input):
如果0< = foo_input< = 100:
return f_input

如果 foo_input>> 100 。但是,它实际上可以不返回任何东西吗?还是一个函数总是不得不返回一些东西?

解决方案

函数总是返回一些东西(至少 None ,在执行过程中已经达到了声明,并且函数结束了)。

另一种情况是它们被异常中断。
在这种情况下,异常处理将支配堆栈,并且您将返回到相应的,除了或者出现一些令人讨厌的错误:)



关于你的问题,我必须说有两种可能性:
要么你有东西要退货,要么你没有。



  • 如果您有要返回的东西,那就这样做,如果不是的话就不要。

  • 如果您依赖返回的具有特定类型的东西,但是您不能返回任何有意义的类型,那么 None 会告诉调用者这是这种情况(
    )没有更好的方式告诉调用者没有是返回然后由 None ,所以检查它,你会没事的)


with a simple filter that test input against a range 0-100.

def foo(foo_input):
    if 0 <= foo_input <= 100:
        return f_input

This returns none if foo_input is > 100. But could it actually 'not' return anything? or does a function allways have to return something?

解决方案

Functions always return something (at least None, when no return-statement was reached during execution and the end of the function is reached).

Another case is when they are interrupted by exceptions. In this case exception handling will "dominate over the stack" and you will return to the appropriate except or get some nasty error :)

Regarding your problem I must say there are two possibilities: Either you have something to return or you do not have.

  • If you have something to return then do so, if not then don't.
  • If you rely on something being returned that has a certain type but you cannot return anything meaningful of this type then None will tell the caller that this was the case ( There is no better way to tell the caller that "nothing" is returned then by None, so check for it and you will be fine)

这篇关于是否有可能不会返回任何东西在python中的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆