为什么只在 public 函数中调用私有函数?

Why only call a private function in a public function?

我在神奇的python-chess库的源代码中徘徊,看到了下面的代码:

def _reset_board(self):
    # code...

def reset_board(self):
    self._reset_board()

reset_board() 函数只做一件事,调用它的私有函数。这背后有什么原因吗?由于 python 不必解析名称 _reset_board(),将代码直接放在私有函数中不会更快吗?

我同意你的看法,这里_reset_board是没有必要的。作者大概是之前在reset_board方法里做了一些wrapping/cleaning,去掉了,没花时间把_reset_board去掉。或者他可能计划在未来添加一些 wrapping/cleaning。

有些项目也可能会根据代码自动生成Documentation,可能会跳过functions/method开头的_,他可能不想发布这个功能的任何文档,但是被开源,这可能不是真正的原因。

_reset_board 存在,因此可以从 reset_board and __init__ 调用它。 __init__不能调用self.reset_board,因为那个方法在subclasses中被重写了,__init__想从自己的_reset_board中调用具体的_reset_board实现=21=]。 (Subclass reset_board 实现可能取决于尚未发生的初始化,以及其他问题。)