2013-04-21 74 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告诉你函数正在返回给它的调用者,它将显示所述函数的最后一行来表示它。