Python: Private Methods and Variables
In Python, we can define private variables and methods. These variables and methods cannot be accessed out of the class or by the inherited class according to the Object-Oriented Paradigm. Things are a bit different in Python.
In python, we can achieve this by using Name Mangling which means adding __ before the variable or method name, let see how
class PPrint: def __init__(self): self.__secret_msg = 'I am alive' # This is a private variable self.check = False def __private_method(self): # This is a private method print('I am private method !') def public_method(self): # This public method, which can access the private method self.__private_method() def public_print(self): print(self.__secret_msg) print(self.check)
In the above class, we define the private methods and variables. Let see how to use them
>>> p = PPrint() >>> p.public_print() I am alive False >>> p.public_method() I am private method ! # so far so good, let see what happends when we try to access these private methods or variables. >>> p.__private_msg Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'PPrint' object has no attribute '__private_msg' >>> p.__private_method() Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'PPrint' object has no attribute '__private_method'
As you can see python does not allow access to these private variables and methods. But, If I say you can access these private variables and methods.
>>> dir(p) ['_PPrint__private_method', '_PPrint__secret_msg', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'check', 'public_method', 'public_print'] # You can see we have private method and variable '_PPrint__private_method', '_PPrint__secret_msg' >>> p._PPrint__private_method() I am private method ! >>> p._PPrint__secret_msg 'I am alive'
So, that's what Name Mangling do it add *<classname>_<method/variablename>.
Conclusion In Python, we can use the name mangling to define the private method and variables, but it not as strict as in other OOP languages. It's almost like a convention which is followed by all python developer. You may also found _ added before the method and variable name, which is just another way to say don't access these methods directly.