为什么python返回None对象?

时间:2014-09-02 13:05:33

标签: python

我有以下功能:

def isEmptyRet(self, cmdr, overIterate):
   //some code which changes the cmdr object
   if (some condition):
     //some code
   else:
     print("got to this point")
     print(cmdr)
     return cmdr

控制台打印以下内容:

got to this point
{'ap': {'file
   //and some other parameters in JSON
  }}}

此功能由以下功能调用:

 def mod(self, tg):
  //some code
     cmdr = self.local_client.cmd(
            tg, func
   )
   //some code..
   cmdr = self.isEmptyRet(cmdr, False)
   print(cmdr)

现在,控制台打印:None

但函数isEmptyRet返回对象,它不是无(正如我们在控制台中看到的那样)。

可能是什么原因?

2 个答案:

答案 0 :(得分:0)

如果您有一个在执行期间没有显式返回值的函数,则返回None值。作为一个例子

def fun(x):
    if x < 10:
        # Do some stuff
        x = x + 10
        # Missing return so None is returned
    else:
        return ['test', 'some other data', x]

print(fun(1))
print(fun(11))

控制台输出将是:

None
['test', 'some other data', 11]

原因是当运行条件x < 10时,没有执行return语句,Python将返回None函数的值

将其与此相比:

def fun(x):
    if x < 10:
        # Do some stuff
        x = x + 10
        # This time is x < 10 we use return to return a result
        return ['test', 'some data', x * 5]
    else:
        return ['test', 'some other data', x]

print(fun(1))
print(fun(11))

输出为

['test', 'some data', 55]
['test', 'some other data', 11]

答案 1 :(得分:-3)

在您的代码中,如果执行流程在isEmptyRet并且在if语句中将评估为true,则函数默认返回None。