Encapsulation unpythonic?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sun Sep 1 21:57:28 EDT 2013


On Sun, 01 Sep 2013 15:13:06 -0400, 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 :-)

Very clever! Pedantic, and an unusual look at what's going on under the 
hood!

I wanted to say it was *not quite correct*, because you can read or write 
directly to the instance dict:

instance.__dict__['name'] = 42


If I understand Python's internals correctly, __dict__ is a slot, and so 
bypasses the usual getattr machinary. But even if so, __dict__['name'] 
uses the dictionary __get/setitem__ method, so it's still a getter/setter 
under the hood.

In any case, even if you are *technically* correct that Python has 
getters and setters under the hood, that's not quite what the discussion 
here is about. But I'm sure you realise that :-)


-- 
Steven



More information about the Python-list mailing list