Python 用于 public 用法的私有方法

Python private method for public usage

我有一个 class A 需要实现方法 meth()。 现在,我不希望我的包的最终用户调用此方法。因此,我必须将此方法设为私有(即 _meth()。我知道它不是真正的私有方法,但约定很重要。)

但问题是我的包中还有另一个 class B 必须调用该方法 _meth()。问题是我现在收到警告方法,说 B 试图访问 class 的受保护方法。因此,我必须使方法 public,即没有前导下划线。这与我的意图相矛盾。

解决这个难题的最pythonic方法是什么?


pylint/your editor/whatever 外部工具向您发出警告这一事实并不会阻止代码执行。我不知道你的编辑器,但 pylint 警告 (注意:"case by case" 意思是:"do not warn me for this line or block",而不是 "totally disable this warning")。

您自己的代码完全可以访问同一包中的受保护属性和方法 - “_protected”命名约定并不意味着 "None shall pass",只是"are you sure you understand what you're doing and willing to take responsability if you break something ?"。由于您是包的 author/maintainer 并且这些是包内访问权限,您显然有权承担此责任;)