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:
- http://stupidpythonideas.blogspot.com.au/2014/01/python-doesnt-have-encapsulation.html
- https://pythonspot.com/encapsulation/
- http://www.python-course.eu/object_oriented_programming.php
- http://stackoverflow.com/questions/1301346/the-meaning-of-a-single-and-a-double-underscore-before-an-object-name-in-python
- http://dirtsimple.org/2004/12/python-is-not-java.html
- http://stackoverflow.com/questions/2627002/whats-the-pythonic-way-to-use-getters-and-setters
- http://programmers.stackexchange.com/questions/120828/are-get-set-methods-a-violation-of-encapsulation