gpt4 book ai didi

Python "private"函数编码约定

转载 作者:行者123 更新时间:2023-12-03 05:39:22 24 4
gpt4 key购买 nike

在编写 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.

关于Python "private"函数编码约定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15047122/

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