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
Here is an example.  If you uncomment the "goodwidget.__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...')

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

Leave a comment

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