Skip to main content
 首页 » 编程设计

Python "private"函数编码约定

2024年02月27日15lexus

在编写 python 模块和函数时,我有一些应该向外部人员公开的“公共(public)”函数,但也有一些其他“私有(private)”函数应该只在本地和内部看到和使用。

据我了解,Python 中没有绝对的私有(private)函数。但是区分“公共(public)”函数和“私有(private)”函数的最佳、最简洁或最常用的风格是什么?

我列出了一些我所知道的风格:

  1. 在模块文件中使用 __all__ 来指示其“公共(public)”函数 ( What's the python __all__ module level variable for? )
  2. 在“私有(private)”函数名称开头使用下划线

人们还有其他想法或惯例吗?

非常感谢!

请您参考如下方法:

来自Python的Class模块文档:

Private” instance variables that cannot be accessed except from inside an object don’t exist in Python. However, there is a convention that is followed by most Python code: a name prefixed with an underscore (e.g. _spam) should be treated as a non-public part of the API (whether it is a function, a method or a data member). It should be considered an implementation detail and subject to change without notice.

Since there is a valid use-case for class-private members (namely to avoid name clashes of names with names defined by subclasses), there is limited support for such a mechanism, called name mangling. Any identifier of the form __spam (at least two leading underscores, at most one trailing underscore) is textually replaced with _classname__spam, where classname is the current class name with leading underscore(s) stripped. This mangling is done without regard to the syntactic position of the identifier, as long as it occurs within the definition of a class.