私人名称修改有什么好处?
Python 为类方法和属性提供私有名称修改。
是否有任何具体情况需要此功能,或者它只是 Java 和 C++ 的延续?
请描述一个应该使用Python名称修饰的用例(如果有的话)?
另外,我对作者只是试图防止意外的外部属性访问的情况不感兴趣。 我认为这个用例与 Python 编程模型不一致。
Python provides private name mangling for class methods and attributes.
Are there any concrete cases where this feature is required, or is it just a carry over from Java and C++?
Please describe a use case where Python name mangling should be used, if any?
Also, I'm not interested in the case where the author is merely trying to prevent accidental external attribute access. I believe this use case is not aligned with the Python programming model.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
部分原因是为了防止意外的内部属性访问。 这是一个示例:
在您的代码中,这是一个库:
在我的代码中,我从您的库类继承:
如果没有私有名称修饰,我意外重用您的名称会破坏您的库。
It's partly to prevent accidental internal attribute access. Here's an example:
In your code, which is a library:
In my code, in which I'm inheriting from your library class:
Without private name mangling, my accidental reuse of your name would break your library.
来自 PEP 8:
(已添加强调)
From PEP 8:
(Emphasis added)
以前的所有答案都是正确的,但这里有另一个原因和例子。 Python 中需要名称重整,以避免因覆盖属性而导致的问题。 换句话说,为了覆盖,Python 解释器必须能够为子方法与父方法构建不同的 id,并使用 __(双下划线)使 python 能够做到这一点。 在下面的示例中,如果没有 __help,此代码将无法工作。
All previous answers are correct but here is another reason with an example. Name Mangling is needed in python because to avoid problems that could be caused by overriding attributes. In other words, in order to override, the Python interpreter has to be able to build distinct id for child method versus parent method and using __ (double underscore) enable python to do this. In below example, without __help this code would not work.
名称修改是为了防止意外的外部属性访问。 大多数情况下,它是为了确保不存在名称冲突。
The name mangling is there to prevent accidental external attribute access. Mostly, it's there to make sure that there are no name clashes.