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?

Here is an example; you can call the file  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):

  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.__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 *