How Do You Use Encapsulation in Python?

Problem scenario
You know about encapsulation.  You know about private methods that are only accessible from inside a class -- not outside.  You want to encapsulate a method in a class in Python.  How do you write such a program?

Solution
"Programmers are most effective if shielded from, not exposed to, the innards of modules not their own." (This was taken from page 272 of The Mythical Man-Month.)

Here is an example; you can call the file encapsulate.py.  If you uncomment the "good_widget.__makeone()", you will see the program fail; you will see the private method __makeone() work in this program if you run it exactly how it appears below (using Python 3):

#!/usr/bin/env python

class WidgetFactory:

  def __init__(self):
    self.__makeone()

  def funtest(self):  # This is a public method.
    print('This widget is working!')

  def __makeone(self):   # This __ syntax tells Python it is a private method.
    print('creating one widget; please wait...')

good_widget = WidgetFactory()
good_widget.funtest()
#good_widget.__makeone()  #  If you uncomment this line, this line will cause the program to throw an error.

For further information:
"Python doesn't have real private methods, so one underline in the beginning of a method or attribute means you shouldn't access this method, because it's not part of the API." (This quote was taken from an external website.) "Other programming languages have protected class methods too, but Python does not." (This quote was taken from https://pythonspot.com/encapsulation/.)

Leave a comment

Your email address will not be published. Required fields are marked *