Encapsulation

Date: February 17th 2016
Last updated: February 17th 2016

I almost overlooked encapsulation. In fact, I got all the way to making my own decorators before reading about encapsulation. It wasn't until I was looking for a definition of object oriented programming that I realized it was even a thing.

What is encapsulation?
Encapsulation if one of four main principles of object oriented programming. Encapsulation can refer to bundling data and methods together, or encaspsulation can refer to access restrictions of attributes or methods of an object. Python doesn't restrict access to attributes and methods. Python uses an underscore idiom to define privacy.

What are attributes and methods with underscores?
No underscores indicates that an attribute is public. One underscore indicates an attribute should be private. Double underscores indicates the attribute is private, but still accessible (with more work).

#!/usr/bin/python3

class Myclass(object):
    def __init__(self):
        self.a = 1 #public
        self._a = 2 #semi-private
        self.__a = 3 #private

m = Myclass()
m.a #prints 1
m._a #prints 2
m.__a #prints Traceback error

# access private attribute with a little more work
m._Myclass__a #prints 3

# access object dictionary
print m.__dict__
#prints {'a': 1, '_Myclass__a': 3, '_a': 2}

Using getters and setters?
In other programming languages getter and setter methods provide an interface to manipulate properties of an object. Python doesn't encourage the use of getters and setters. But when they are used, it appears best practice to use the @property decorators. I recommend reading this article.

Useful resources:

results matching ""

    No results matching ""