What is the benefit of private name mangling?

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.

Leave a Comment