Search code examples
pythoncpythonpython-internalsprivate-methods

How python resolves private(double underscore) methods inside a class?


Consider the following class

class Foo(object):

    @staticmethod
    def __is():
        print('__is')

    def m(self):
        Foo.__is()  # executes


Foo.__is()  # fails because of mangling

print(Foo.__dict__.keys())

Foo.__is() when it is run after the class is defined, it fails because of name mangaling. How is python interpreter able to resolve Foo.__is() inside methods but not outside the class?


Solution

  • Name mangling for names starting with __ inside a class, is implemented by rewriting this names to the mangled form, inside the class ONLY. So your Foo.__is inside the class gets replaced by _Foo__is that is now present in the class __dict__. That attribute is accessible either inside or outside the class, so no private protection. But after replacement the __is name does not exist anywhere (I think), that's why it does not work from outside.

    From the Python help:

    "__*" Class-private names. Names in this category, when used within the context of a class definition, are re-written to use a mangled form to help avoid name clashes between “private” attributes of base and derived classes. See section Identifiers (Names).

    Also see my comment to errors in your code snippet.