什么时候使用 python 拆分名称?

When are python sunder names used?

在Python中,有单前导下划线、双前导下划线、双前导+双尾随下划线和单尾随下划线的约定。 What is the meaning of a single- and a double-underscore before an object name?.

的答案中概述了其中的许多内容

但是单前导+单尾随下划线的含义或约定是什么?我第一次看到它们的用法是在 enum module:

8.13.15.3.2. Supported _sunder_ names

  • _name_ – name of the member
  • _value_ – value of the member; can be set / modified in new
  • _missing_ – a lookup function used when a value is not found; may be overridden
  • _ignore_ – a list of names, either as a list() or a str(), that will not be transformed into members, and will be removed from the final class
  • _order_ – used in Python 2/3 code to ensure member order is consistent (class attribute, removed during class creation)
  • _generate_next_value_ – used by the Functional API and by auto to get an appropriate value for an enum member; may be overridden

我以前没有见过这样的单前单尾下划线 sunder 名称。它们是否以任何特殊方式处理,或者具有不同于任何其他与下划线相关的命名约定的隐含含义?它们与完全没有下划线有何不同?

他们没有受到任何特殊对待。它们被枚举模块使用,以便

  • 不会被意外覆盖

例如

class Status(Enum):
    alive = auto()
    dead = auto()
    missing = auto()

可以看到Status.missingStatus._missing_是不同的对象。如果枚举方法 _missing_ 被命名为 missing,我们将重写它。

  • 不显示为私人。 python 中的名字 _value 被认为是私有的。为了表示这些不是私有的(同样,用户可能希望枚举值是私有的),它们被赋予了 sunder names

  • 其他选项,如 __double_leading_underscore__dunder__ 在 python 中也有特殊含义,如您上面所述。 Enum 中的 _sunder_ 方法类似于纯 python 的 __dunder__ 协议,但未被语言保留。

基本上,这是一个避免属性名称冲突而又不给人错误印象的选项。