gpt4 book ai didi

python - 有什么理由让 Python 3 执行一条语句两次吗?

转载 作者:太空宇宙 更新时间:2023-11-04 01:28:10 24 4
gpt4 key购买 nike

我有一个函数:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com