Possible Duplicate:
What is the benefit of private name mangling in Python?
While I was playing with python, I found that if class
or instance
variable-name starts with 2 underscores, they will be renamed so as to be preceded by '_'.
eg
class Test(object):
__attribute = "dunderscored"
def __init__(self, value=0):
self.__instance_attribute = value
test_instance = Test()
then both the variables will be renamed to
test_instance._Test__attribute
and test_instance._Test__instance_attribute
Why is there such a behaviour/feature? Is there any need of that, or any special use intended of that?
I can think of a use case that when different classes have some attribute with a generic name, eg. value, id, member in common, but for some function/method we are expecting/assuming only one of these classes. In this case there is a chance that type checking is not being done and when another class instance is passed to it(maybe by mistake) may result in errors and/or undesired behaviour.
But apart from this use case I don't see any benefit of this special behaviour. The behaviour looks like a feature, pretty fundamental one, and I feel like I am missing something here. If it's a feature what is the use of it? Any typical use case?