Encapsulation unpythonic?
Ethan Furman
ethan at stoneleaf.us
Sun Sep 1 16:33:25 EDT 2013
On 09/01/2013 12:13 PM, Roy Smith wrote:
> In article <mailman.455.1378062400.19984.python-list at python.org>,
> Ethan Furman <ethan at stoneleaf.us> wrote:
>
>> On 09/01/2013 03:09 AM, Fabrice Pombet wrote:
>>>
>>> So I guess that we are actually all agreeing on this one.
>>
>> No, we are not.
>>
>> "encapsulation" != "inaccessible except by getters/setters"
>
> Nothing is accessible in Python except via getters and setters. The
> only difference between Python and, say, C++ in this regard is that the
> Python compiler writes them for you most of the time and doesn't make
> you put ()'s at the end of the name :-)
class Javaesque:
__value = None
def get_value(self):
return self.__value
def set_value(self, new_value):
validate(new_value)
self.__value = new_value
class ProtectedPython:
_value = None
@property
def value(self):
return self._value
@value.setter
def value(self, new_value)
validate(new_value)
self._value = new_value
class PlainPython:
value = None
In the Javaesque class we see the unPythonic way of using getters/setters; in the ProtectedPython* class we see the
pythonic way of providing getters/setters**; in the PlainPython class we have the standard, unprotected, direct access
to the class attribute.
No where in PlainPython is a getter/setter defined, nor does Python define one for us behind our backs.
If you have evidence to the contrary I'd like to see it.
* Not the best name, but oh well.
** In Python, using @property makes getter/setter usage look just like normal attribute usage, which is cool.
--
~Ethan~
More information about the Python-list
mailing list