3 ms·
Mangling of double-underscore names isn't there to provide access control like in Java or C++. Mangling of double-underscore names is explicitly documented as
by ubernostrum 8y ago
Mangling of double-underscore names isn't there to provide access control like in Java or C++.
Mangling of double-underscore names is explicitly documented as existing "to avoid name clashes of names with names defined by subclasses". The use case there is a parent class defines a method called, say, "foo". Other methods of the parent call self.foo(). Then a subclass overrides foo() but changes the signature (say, by adding a new non-optional argument), and doesn't override the other methods that call self.foo(). Without name mangling or something like it, this breaks. If the parent class either names the method "__foo" or aliases a copy of the parent class' implementation to "__foo", and calls self.__foo(), name mangling ensures those calls will find the right (as in, compatible) implementation of the method based on where the call came from.
That's it. That's the one and only use case for invoking name mangling in Python, and it's a thing that generally you shouldn't be doing anyway.
Name mangling also isn't invoked for leading + trailing double underscore -- a "__foo__()" method would not get mangled.