Encapsulation unpythonic?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Wed Aug 21 22:06:24 EDT 2013


On Wed, 21 Aug 2013 12:52:06 -0400, random832 wrote:

> On Mon, Aug 19, 2013, at 3:05, Steven D'Aprano wrote:
>> In this toy example, both parties are at fault: the author of Parrot
>> for unnecessary data-hiding of something which is so obviously a useful
>> piece of information and should be part of the public interface,
> 
> It may wish to be notified when its name changes, and so have a name
> property. The subclass may want to use a variable called _name for some
> other purpose. (maybe "name" isn't the best example).

Such a "name" property would be a public interface, and so a Good Thing. 
However, my toy example was of a case where something *obviously useful* 
was being left out of the public interface. If it were a public property, 
it wouldn't be the case that it were left out, would it?


> Examples often look pathological when you simplify out the bit that
> makes them make sense.

Naturally :-) 

I did call this a toy example. Nevertheless, in the Real World, data 
hiding can sometimes be a bit of a religion. Not all cases where people 
try various tricks and hacks to gain access to "private" and "protected" 
members are specious.

The whole Java getter and setter philosophy is based on the idea that 
everything, even the most innocuous data attribute, ought to be private, 
with a computed getter and setter Just In Case some day in the future you 
want to wrap access in code. In Python, you can turn an attribute into a 
computed property with no change to the public interface. In Java, you 
can't.


-- 
Steven



More information about the Python-list mailing list