Python为类方法和属性提供私有名称修饰。
是否有需要此功能的具体案例,或者它只是 Java 和 C++ 的继承?
请描述一个应该使用 Python 名称修饰的用例,如果有的话?
另外,我对作者只是试图防止意外的外部属性访问的情况不感兴趣。我相信这个用例与 Python 编程模型不一致。
Python为类方法和属性提供私有名称修饰。
是否有需要此功能的具体案例,或者它只是 Java 和 C++ 的继承?
请描述一个应该使用 Python 名称修饰的用例,如果有的话?
另外,我对作者只是试图防止意外的外部属性访问的情况不感兴趣。我相信这个用例与 Python 编程模型不一致。
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.
From PEP 8:
If your class is intended to be subclassed, and you have attributes that you do not want subclasses to use, consider naming them with double leading underscores and no trailing underscores. This invokes Python's name mangling algorithm, where the name of the class is mangled into the attribute name. This helps avoid attribute name collisions should subclasses inadvertently contain attributes with the same name.
(Emphasis added)
以前的所有答案都是正确的,但这里有一个例子的另一个原因。在 python 中需要 Name Mangling,因为以避免可能由覆盖属性引起的问题。换句话说,为了覆盖,Python 解释器必须能够为子方法和父方法构建不同的 id,并且使用 __(双下划线)使 python 能够做到这一点。在下面的示例中,如果没有 __help,此代码将无法工作。
class Parent:
def __init__(self):
self.__help("will take child to school")
def help(self, activities):
print("parent",activities)
__help = help # private copy of original help() method
class Child(Parent):
def help(self, activities, days): # notice this has 3 arguments and overrides the Parent.help()
self.activities = activities
self.days = days
print ("child will do",self.activities, self.days)
# the goal was to extend and override the Parent class to list the child activities too
print ("list parent & child responsibilities")
c = Child()
c.help("laundry","Saturdays")
名称修改是为了防止意外的外部属性访问。大多数情况下,它是为了确保没有名称冲突。