2

我有一个功能:

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 启动,我得到以下 I/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 行的语句被执行了两次。为什么会这样?

4

1 回答 1

3

该行不再被执行。

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

这意味着:这是函数的返回点,因为您没有添加 a return(因为__init__方法应该只返回 None 无论如何)。

如果您检查字节码,它会在最后显示类似的内容:

         28 LOAD_CONST               1 (None) 
         31 RETURN_VALUE

None这意味着即使未指定该函数也会实际返回。

所以,pdb告诉你函数正在返回给它的调用者,它将显示所述函数的最后一行来表示它。

于 2013-04-21T00:46:27.513 回答