In an object oriented python program, you can restrict access to methods and variables. This can prevent the data from being modified by accident and is known as encapsulation.   Let’s start with an example.

Related Courses:
Complete Python Bootcamp: Go from zero to hero in Python 3

Private methods

encapsulation. Restricted accesss to methods or variables

We create a class Car which has two methods:  drive() and updateSoftware().  When a car object is created, it will call the private methods __updateSoftware().  

This function cannot be called on the object directly, only from within the class.

#!/usr/bin/env python
class Car:
def __init__(self):
def drive(self):
print 'driving'
def __updateSoftware(self):
print 'updating software'
redcar = Car()
#redcar.__updateSoftware()  not accesible from object.

This program will output:

updating software

Encapsulation prevents from accessing accidentally, but not intentionally.

The private attributes and methods are not really hidden, they’re renamed adding “_Car” in the beginning of their name.

The method can actually be called using redcar._Car__updateSoftware()

Private variables

Class with private variables

Variables can be private which can be useful on many occasions. A private variable can only be changed within a class method and not outside of the class.

Objects can hold crucial data for your application and you do not want that data to be changeable from anywhere in the code.
An example:

#!/usr/bin/env python
class Car:
__maxspeed = 0
__name = ""
def __init__(self):
self.__maxspeed = 200
self.__name = "Supercar"
def drive(self):
print 'driving. maxspeed ' + str(self.__maxspeed)
redcar = Car()
redcar.__maxspeed = 10  # will not change variable because its private

If you want to change the value of a private variable, a setter method is used.  This is simply a method that sets the value of a private variable.

#!/usr/bin/env python
class Car:
__maxspeed = 0
__name = ""
def __init__(self):
self.__maxspeed = 200
self.__name = "Supercar"
def drive(self):
print 'driving. maxspeed ' + str(self.__maxspeed)
def setMaxSpeed(self,speed):
self.__maxspeed = speed
redcar = Car()

Why would you create them? Because some of the private values you may want to change after creation of the object while others may not need to be changed at all.

Python Encapsulation

To summarize, in Python there are:

Type Description
public methods Accessible from anywhere
private methods Accessible only in their own class. starts with two underscores
public variables Accessible from anywhere
private variables Accesible only in their own class or by a method if defined. starts with two underscores

Other programming languages have protected class methods too, but Python does not.

Encapsulation gives you more control over the degree of coupling in your code, it allows a class to change its implementation without affecting other parts of the code.


19 thoughts on “Encapsulation

  1. Amit - September 24, 2015

    class Person:
    __name #variable

    class Programmer(Person)
    self_Person__name ——> meaning full explanation please for this

    1. Frank - September 24, 2015

      Hi Amit,
      The class Programmer inherits from the class Person. The Person class has a variable called name. Because Programmer inherits from Person, it has access to the name variable. For more on inheritance, read here.

  2. Sajan Bhagat - August 7, 2015

    first of all __maxspeed is private but i’m still able to access it with object name & another thing when i used print(redcar.__maxspeed) it prints updated value 10 could you please explain the behaviour

  3. Terry - August 1, 2015

    Does Python support namespaces?

    1. Frank - August 1, 2015

      Hi Terry,

      Yes there are namespaces, but there are a variety of ways to implement them.
      I would recommend the third method because it’s the most clean solution.

      Method 1: Use dictionary
      Everything is an object in Python, a dictionary can act as a namespace.

      #!/usr/bin/env python
      class Person:
          def sayHi(self):
      person = Person()
      def python():
      a_namespace = {'person':person, 'python': python}

      Method 2: Use packages
      Create a directory /example/demo/ for your package. Inside it create a file called __init__.py with this contents:

      #!/usr/bin/env python
      def hello():
          print('Hello world')
      Then on the /example/ directory create a file test.py with this contents:
      import demo

      Method 3: Use pkgutil
      If you use pkgutil, you can create nested packages. Create a directory using this structure

      • /example/hello/
      • /example/hello/__init__.py
      • /example/hello/english/
      • /example/hello/english/__init__.py
      • /example/hello/dutch/
      • /example/hello/dutch/__init__.py
      • /example/test.py

      In /example/hello/__init__.py put:

      import pkgutil
      __path__ = pkgutil.extend_path(__path__, __name__)

      In /example/hello/english/__init__.py put:

      def hello():

      In /example/hello/dutch/__init__.py put:

      def hello():

      Your package is now complete. You can use nested namespaces.
      Add this to /example/test.py and execute it:

      import hello.english
      import hello.dutch
  4. Crysis - July 25, 2015

    It’s weird that for python the default access for a variable is public…

    1. Frank - July 25, 2015

      Hi! It’s cultural, in both Python and Java nothing prevents you from declaring all variables public, encapsulation is not strictly enforced in either language. In Java variables are private by default, in Python private variables are not enforced. In practice there is not a lot of difference because the developer has the authority on the code.

      1. Terry - August 1, 2015

        And in C++ a struct is a class where all the members are public by default.

  5. Naveen Kerati - June 30, 2015

    so __ before a method or variable is considered as a private members is it…?

    1. Frank - June 30, 2015

      Yes, if you put __ before a method or variable it is a private member. This means you can only access it using a method.

  6. Tomislav - June 20, 2015

    “If you want to change the value of a private value, an setter method is used. This is simply a method that sets the value of a private value.”

    there is a typo –> change the value of a private value –> change the value of a private variable

    1. Frank - June 20, 2015

      Thanks Tomislav! I updated it

Leave a Reply