Encapsulation unpythonic?

Steven D'Aprano steve at pearwood.info
Mon Aug 19 03:05:48 EDT 2013


On Sun, 18 Aug 2013 18:15:10 +0100, Joshua Landau wrote:

> On 17 August 2013 17:17, Steven D'Aprano
> <steve+comp.lang.python at pearwood.info> wrote:
>> On Sat, 17 Aug 2013 05:26:32 -0700, fsaldan1 wrote:
>>> how do I
>>> deal with the fact that other programmers can easily alter the values
>>> of members of my classes?
>> ...
>> If they insist on messing with your private single-underscore
>> _attributes, you can't stop them, but that's okay, you don't have to be
>> sympathetic when they shoot their foot off. Just slap them with a large
>> halibut[1] and laugh.
> 
> I know I've cropped your points but I just want to mention here that the
> only reason to monkey-patch code in these ways where you'd want to stop
> them is when the alternative is *worse*. It's like removing railings
> from a cliff to stop people hitting the bars.



I'm not actually talking about monkey-patching. I'm talking about just 
normal inheritance of classes. E.g. If a module has this class:


class Parrot:
    def __init__(self):
        self._name = "Polly"
    def talk(self):
        print "%s wants a cracker!" % self._name


I might be tempted to do this:

class MyParrot:
    def __init__(self):
        super(MyParrot, self).__init__()
        self._name = "George"


No monkey-patching involved. But, if the author of Parrot class changes 
his implementation and gets rid of "_name", or even makes it public 
"name", my subclass will stop working. Sucks to be me.

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, and me for 
nevertheless ignoring that warning and using the private attribute in my 
own code. More realistic examples may be different.



-- 
Steven



More information about the Python-list mailing list