Objectives

Back to basics. A really small post to explain the concept of private method and functions in Python.

What is a private method / function ?

A private function is a function that can be called only inside his module.
A private class method is a method that can be called only inside his class.
The concept of protected method doesn't exist in Python (accessible within his class and all classes that inherit his classes).

How to make a method / function pivate ?

Really easy ! Just add two underscore before the method or function name and it become private (also works for attributes), do not add two uderscores at the end of the name, it's for builtin/special method.

Summary

  • A private functions or method is private only because of his name.
  • Just add two underscore before a method, function or attribute to make it private.
  • Do not add two underscore at the end of a method, functions or attribute name.

For further informations

If you add just one underscore before a function, method or attribute (ex: def _hello()... instead of def __hello(), it's still considered private, but just for convention. It change nothing for python internaly, except that from M import * does not import objects whose name starts with an underscore.
Below an illustration inspired from stackoverflow:

Library & constant definition
    
     class Test(object):
         def __init__(self):
              self.__a = 'a' # Real private attribute
              self._b = 'b' # "Weak" private attribute (only by convention)
     
     >>> t = Test()
     >>> t._b # We can call weakly private attribute...
     'b'
     
     >>> t.__a # But it is not possible when the attribute is really private (two underscore)
      Traceback (most recent call last):
        File "", line 1, in 
      AttributeError: 'Test' object has no attribute '__a'