Information Hiding in Python

05 min read

By default, all attributes in Python are "public". This means that all attributes of a class instance are accessible without any restrictions. It also implies that everything defined in a base class is inherited and accessible within a derived class. This behaviour is often undesirable in object-oriented applications because it exposes the internal implementation of an object and can lead to namespace conflicts between objects defined in a derived class and those defined in a base class.

To fix this problem, all names in a class that start with a double underscore, such as __FACEPrep, are automatically mangled to form a new name of the form _Classname__FACEPrep. This effectively provides a way for a class to have private attributes because private attribute names used in derived class won't collide with the same private names used in the base class. 

For example,

class A(object):
         def __init__(self):
                self.__X= 3                              # Mangled to self._A__X

class B(A):
          def __init__(self):
                     A.__init__self(self)
                        self.__X = 37                  # Mangled to self._B__X

 

Although this scheme provides the illusion of data hiding, there is no strict mechanism in place to prevent access to the "private" attributes of a class. In particular, if the name of the class and corresponding private attribute are known, they can be accessed using the mangled name.

 

POST A NEW COMMENT
     
  • Input (stdin)

    Output (stdout)


    Input (stdin)

    Your Output (stdout)

    Expected Output

    Compiler Message

    Input (stdin)

    2    3

    Your Output (stdout)

    5

    Expected Output

    5

    Compiler Message

    5

    Error