从文档私有变量中强调名称重整中的问题
Underscores Problem in Name Mangling from docs Private Variables
Docs->9.Classes->9.6 Private Variables
以下几行(第 3 行到第 5 行)对我来说意义为零:
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.
如果 classname 是当前的 class 为什么它说 前导下划线被删除 ?文中大家可以看到_classname__spam
元素前面有下划线
编辑
不知何故应该有 class 名称带有前导下划线,例如 __Welcome 但在学习材料中我总是犯下这样的例子:
class NamingNow:
pass
...没有下划线。然而,当我使用 dir
函数时,我得到类似
的东西
>>> dir(Mapping)
['_Mapping__update', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'update']
此规则是否适用于此 __class__
事物?
意思是如果 class 名称本身包含前导下划线,它们将被去除,但另一个下划线将始终放在前面。因此,名为 _MyClass
的 class 的属性将被破坏为 _MyClass_spam
,而不是 __MyClass_spam
。
Docs->9.Classes->9.6 Private Variables
以下几行(第 3 行到第 5 行)对我来说意义为零:
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.
如果 classname 是当前的 class 为什么它说 前导下划线被删除 ?文中大家可以看到_classname__spam
元素前面有下划线
编辑
不知何故应该有 class 名称带有前导下划线,例如 __Welcome 但在学习材料中我总是犯下这样的例子:
class NamingNow:
pass
...没有下划线。然而,当我使用 dir
函数时,我得到类似
>>> dir(Mapping)
['_Mapping__update', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'update']
此规则是否适用于此 __class__
事物?
意思是如果 class 名称本身包含前导下划线,它们将被去除,但另一个下划线将始终放在前面。因此,名为 _MyClass
的 class 的属性将被破坏为 _MyClass_spam
,而不是 __MyClass_spam
。