为什么python返回None对象



我有以下功能:

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返回的对象不是none(正如我们在控制台中看到的)。

原因是什么?

如果函数在执行过程中没有显式返回值,则会返回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]

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

最新更新