Encapsulation


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.

Private methods

encapsulation
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):
        self.__updateSoftware()
 
    def drive(self):
        print 'driving'
 
    def __updateSoftware(self):
        print 'updating software'
 
redcar = Car()
redcar.drive()
#redcar.__updateSoftware()  not accesible from object.

This program will output:

updating software
driving

The private method  __updateSoftware() can only be called within the class itself.  It can never be called from outside the class.

Private variables

encapsulation-example
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.drive()
redcar.__maxspeed = 10  # will not change variable because its private
redcar.drive()

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()
redcar.drive()
redcar.setMaxSpeed(320)
redcar.drive()

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.

Quiz


17 thoughts on “Encapsulation

  1. Sadia - February 20, 2016

    Hi Frank,
    i am getting problem in file handling. i have written program which count number of lines and total words in file but it is not giving me correctly the number of words. my txt file is :

    this is a text file. i have to count its lines and words.
    this is a text file. i have to count its lines and words.

    this program is giving me 58 words while there are not 58 words. Secondly when i write filename.read instead of filename.readlines then it does not give me correct number of lines. why?

    count=0
    filename=open("mfile.txt",'r')
    handle=filename.readlines()
    #print(handle)
    for line in handle:
        count+=1
    print(count)
     
    count_word=0
    for word in line:
        count_word=count_word+1
    print(count_word)
    1. Frank - February 25, 2016

      If you print word inside the for word loop, it will show it splits the line into single characters. To split into words use this:

      count=0
      filename=open("mfile.txt",'r')
      handle=filename.readlines()
      #print(handle)
      for line in handle:
          count+=1
       
      print(count)
       
      count_word=0
      words = line.split(' ')
      for word in words:
          print word
          count_word=count_word+1
      print(count_word)

      read() and readlines() are different methods. read() takes x characters from a file. readlines() reads the whole file and splits by newlines.

      1. Sadia - February 27, 2016

        Many thanks 🙂

  2. Jacky - December 16, 2015

    Hi,Frank
    What’s the text font in the source code?

    1. Frank - December 19, 2015

      Hi Jacky, I think it’s monospace

  3. 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.