私有名称重整有什么好处? [英] What is the benefit of private name mangling?
问题描述
Python 为类方法和属性提供私有名称修改.
Python provides private name mangling for class methods and attributes.
是否有任何具体情况需要此功能,还是只是从 Java 和 C++ 继承而来?
Are there any concrete cases where this feature is required, or is it just a carry over from Java and C++?
请描述一个应该使用 Python 名称修饰的用例(如果有)?
另外,我对作者只是试图防止意外的外部属性访问的情况不感兴趣.我相信这个用例与 Python 编程模型不一致.
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.
推荐答案
部分是为了防止意外的内部属性访问.举个例子:
It's partly to prevent accidental internal attribute access. Here's an example:
在您的代码中,这是一个库:
In your code, which is a library:
class YourClass:
def __init__(self):
self.__thing = 1 # Your private member, not part of your API
在我的代码中,我从您的库类继承:
In my code, in which I'm inheriting from your library class:
class MyClass(YourClass):
def __init__(self):
# ...
self.__thing = "My thing" # My private member; the name is a coincidence
如果不修改私人名称,我不小心重复使用你的名字会破坏你的图书馆.
Without private name mangling, my accidental reuse of your name would break your library.
这篇关于私有名称重整有什么好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!