Today I see that – python add _$CLASSNAME$ to methods with name with __.
Simple example:
>>> class A:
... def a(self):
... self.b()
... def b(self):
... print('A.b')
...
>>> class B(A):
... def b(self):
... print('B.b')
...
>>> B().a()
B.b
That work, but:
>>> class A:
... def a(self):
... self.__b()
... def __b(self):
... print('A.b')
...
>>> class B(A):
... def __b(self):
... print('B.b')
...
>>> B().a()
A.b
Why? I don’t know, so I dir’ed it. Here it is:
>>> print([fn for fn in dir(B) if fn[-2:] != '__'])
['_A__b', '_B__b', 'a']
Why python do that? Is there way to bypass that?
It’s called name mangling and done to prevent accidental name collisions with parent and child classes. You cannot (and should not, a lot of perfectly fine code uses it) disable it. You can circumvent it, but you should not do that either (it’s extremely ugly, you can avoid it, and when you need access to it you shouldn’t permit name mangling in the first place). Just use a single underscore for private functions you want to use anywhere but immediately inside the class.
See the tutorial but ignore any reference to this denoting a “private” variable. That’s not what it’s used for unless you use
privatein the C++/Java/C#/… sense ofprivatevariables (as opposed toprotectedwhich are visible to child classes) being hidden from child classes. Even then it’s a flawed analogy.