Python classes do not have the concept of public / private, so they tell us not to touch what starts with underscores if we didn't create one. But does this not require a complete knowledge of all the classes from which we inherit, directly or indirectly? Witness:
class Base(object): def __init__(self): super(Base, self).__init__() self._foo = 0 def foo(self): return self._foo + 1 class Sub(Base): def __init__(self): super(Sub, self).__init__() self._foo = None Sub().foo()
A TypeError is TypeError occur when evaluating None + 1 . Therefore, I should know that _foo exists in the base class. To get around this, you can use __foo , which solves the problem by changing the name. It seems, if not an elegant, acceptable solution. However, what happens if Base inherits from a class (in a separate package) called Sub ? Now __foo in my Sub overrides __foo in grandparent Sub .
This means that I must know the entire inheritance chain, including all the "private" objects that everyone uses. The fact that Python is dynamically typed makes this even more difficult since there are no ads to search for. However, the worst part is probably the fact that Base can inherit from object right now, but in some future version it will switch to inheritance from Sub . It is clear that if I know that Sub inherited from, I can rename my class, however annoying it may be. But I do not see in the future.
Is this not the case when a true type of private data prevents the problem? How, in Python, can I be sure that I am not accidentally stepping on someone if these fingers can exist at some point in the future?
EDIT: I, apparently, did not specify the main question. I am familiar with the name change and the difference between blue and double underscore. The question is, how can I deal with the fact that I can run into classes whose existence I do not know right now? If my parent class (which is in the package that I did not write) starts to inherit from the class with the same name as my class, even using mangling will not help. I am mistaken in considering this as a (angular) case that true private members allow, but does Python have problems with?
EDIT: as requested, the following example is given:
parent.py file:
class Sub(object): def __init__(self): self.__foo = 12 def foo(self): return self.__foo + 1 class Base(Sub): pass
sub.py file:
import parent class Sub(parent.Base): def __init__(self): super(Sub, self).__init__() self.__foo = None Sub().foo()
Grandparent foo is called, but my __foo .
Obviously, you will not write such code yourself, but parent can be easily provided by a third party, the details of which can be changed at any time.