为什么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(我们在控制台中看到了这一点)。
这可能是什么原因呢?
2 个回答
-3
在你的代码中,如果执行流程进入了 isEmptyRet
,并且 if
语句的判断结果为真,那么这个函数默认会返回 None。
1
如果你有一个函数在执行过程中没有明确返回任何值,那么它会返回一个 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]