Reputation: 117028
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.
Upvotes: 17
Views: 8269
Reputation: 22392
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.
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")
Upvotes: 4
Reputation: 281535
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.
Upvotes: 30
Reputation: 91028
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)
Upvotes: 15
Reputation: 172279
The name mangling is there to prevent accidental external attribute access. Mostly, it's there to make sure that there are no name clashes.
Upvotes: -1