2014-09-02 181 views
-4

我有以下功能:为什么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返回对象,它不是无(如我们在控制台中看到的)。

可能是什么原因?

+0

不,只有当它在'else'块返回的东西。假设你在'if'块中没有return语句。 – 2014-09-02 13:08:17

+0

它打印“到了这一点”? – Don 2014-09-02 13:08:22

+0

@Don是的,它打印.. – 2014-09-02 13:09:01

回答

-3

在您的代码中,如果执行流程进入isEmptyRet并且if语句将计算为true,那么函数默认返回None。

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在运行时出现的是被执行和Python将返回None的价值没有return声明功能

与此相比,这样的:

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] 
相关问题