2013-04-21 67 views
2

我有一個函數:Python 3會執行兩次語句嗎?

def turn(self, keyEvent): 

    if (keyEvent.key == pygame.locals.K_UP) and \ 
     (self.body[0].direction != Directions.DOWN): 
     self._pivotPoints.append(PivotPoint(self.body[0].location, \ 
     Directions.UP)) 
     print("Placing pivot point up") 

    #elif chain for the down left and right button presses omitted 
    #code is the same for each input 

創建下面的類的實例:

class PivotPoint: 
    def __init__(self, location, \ 
       direction): 
     """When a body part reaches a pivot point, it changes directions""" 
     pdb.set_trace() 
     self.location = location 
     self.direction = direction 

當我運行這段代碼,PDB火了,我得到我的下列順序/ O:

> /home/ryan/Snake/snake.py(50)__init__() 
-> self.location = location 
(Pdb) step 
> /home/ryan/Snake/snake.py(51)__init__() 
-> self.direction = direction 
(Pdb) step 
--Return-- 
> /home/ryan/Snake/snake.py(51)__init__()->None 
-> self.direction = direction 
(Pdb) step 
> /home/ryan/Snake/snake.py(89)turn() 
-> print("Placing pivot point right") 

第51行的聲明正在執行兩次。這是爲什麼?

+0

'self.direction'屬性? – Mehrdad 2013-04-21 00:36:03

+0

它只是函數的最後一行,它將返回'None',因爲沒有指定'return'。有沒有再次運行線 – JBernardo 2013-04-21 00:36:14

+0

@Mehrdad它的目的是成爲一個變量。如果我的語法錯誤,它可能是解釋者的財產,但我對此表示懷疑。截至目前,我已經發布了整個課程。 – Ryan 2013-04-21 00:38:43

回答

3

該行不再被執行。

> /home/ryan/Snake/snake.py(51)__init__()->None 

這意味着:這是函數的返回點,因爲你沒有添加return(因爲__init__方法應該只返回無反正)。

如果檢查字節碼,它會顯示類似的東西在最後:

  28 LOAD_CONST    1 (None) 
     31 RETURN_VALUE 

意味着函數實際上將返回即使沒有指定None

因此,pdb告訴你函數正在返回給它的調用者,它將顯示所述函數的最後一行來表示它。