我有一个功能:
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 行的语句被执行了两次。为什么会这样?
最佳答案
该行不会再次执行。
> /home/ryan/Snake/snake.py(51)__init__()->None
这意味着:这是函数的返回点,因为您没有添加 return
(因为 __init__
方法无论如何都应该只返回 None)。
如果你检查字节码,它会在末尾显示类似的内容:
28 LOAD_CONST 1 (None)
31 RETURN_VALUE
意味着即使未指定,该函数实际上也会返回None
。
因此,pdb
告诉您该函数正在返回其调用者,并且它将显示该函数的最后一行来表示这一点。
关于python - Python 3 有什么原因会执行一条语句两次吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16126752/