Note that in Python there is no such thing as a "private method". Double underline is just the name:
>>> class A(object): ... def __foo(self): ... pass ... >>> a = A() >>> A.__dict__.keys() ['__dict__', '_A__foo', '__module__', '__weakref__', '__doc__'] >>> a._A__foo()
Thus, the __ prefix is ββuseful when you need manipulation to occur, for example, so that you don't encounter names up or down the inheritance chain. For other purposes, one underline would be better, IMHO.
EDIT, regarding the confusion on __ , PEP-8 is quite clear:
If your class is intended to be a subclass and you have attributes that you do not want to use subclasses, consider their double leading underscores and the absence of underscores. This calls the Python Name Rename Algorithm, where the class name is mutilated into the attribute name. This helps to avoid a collision attribute name should subclasses inadvertently contain attributes with the same name.
Note 3: Not everyone likes name manipulation. Try to balance the need to avoid accidental name conflicts with the potential use of advanced subscribers.
So, if you do not expect the subclass to accidentally override your own method with the same name, do not use it.
Daniel Kluev Aug 02 '10 at 5:51
source share