Why do we even need to use encapsulation in Python?
What is encapsulation in Python, and why should I care?
How do I achieve encapsulation in Python in my code?
Python has encapsulation - you are using it in your class.
What it doesn't have is access control such as private and protected attributes. However, in Python, there is an attribute naming convention to denote private attributes by prefixing the attribute with one or two underscores, e.g:
self._a
self.__a
A single underscore indicates to the user of a class that an attribute should be considered private to the class, and should not be accessed directly.
A double underscore indicates the same, however, Python will mangle the attribute name somewhat to attempt to hide it.
class C(object):
def __init__(self):
self.a = 123 # OK to access directly
self._a = 123 # should be considered private
self.__a = 123 # considered private, name mangled
>>> c = C()
>>> c.a
123
>>> c._a
123
>>> c.__a
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'C' object has no attribute '__a'
>>> c._C__a
123
You can see in the last example that the name was changed from __a to _C__a, although it is still accessible within the class as self.__a.
Well, Python does not have encapsulation as a sort of "philosophical" decision, in the same way that we use duck typing a lot. Personally I don't see the point of using private or protected arguments in a Python code.
Speaking of your code, it seems to work fine with the following getters and setters:
def set_a(self, v):
self.a = v
def get_a(self):
return self.a
if you make the following modification to your last line of __ getattribute __(self, name):
return object.__getattribute__(self, name)
However, you can use sort of a notion of variable-protecting, if you prefix your private variables with __, as mhawke mentioned. Plus, Daniel's comment points out a limitation of your list arguments. You could keep the protected "get/set" behaviour by adding "private" and "protected"in your private list.