2014-09-02 180 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] 
相關問題