Protecting instance variables

Nikolaus Rath Nikolaus at rath.org
Mon Jul 28 06:23:21 EDT 2008


Hi,

Sorry for replying so late. Your MUA apparently messes up the
References:, so I saw you reply only now and by coincidence.

"Diez B. Roggisch" <deets at nospam.web.de> writes:
> Nikolaus Rath schrieb:
>> Hello,
>>
>> I am really surprised that I am asking this question on the mailing
>> list, but I really couldn't find it on python.org/doc.
>>
>> Why is there no proper way to protect an instance variable from access
>> in derived classes?
>>
>> I can perfectly understand the philosophy behind not protecting them
>> from access in external code ("protection by convention"), but isn't
>> it a major design flaw that when designing a derived class I first
>> have to study the base classes source code? Otherwise I may always
>> accidentally overwrite an instance variable used by the base class...
>
> Here we go again...
>
> http://groups.google.com/group/comp.lang.python/browse_thread/thread/188467d724b48b32/
>
> To directly answer your question: that's what the __ (double
> underscore) name mangling is for.


I understand that it is desirable not to completely hide instance
variables. But it seems silly to me that I should generally prefix
almost all my instance variables with two underscores.

I am not so much concerned about data hiding, but about not
accidentally overwriting a variable of the class I'm inheriting from.
And, unless I misunderstood something, this is only possible if I'm
prefixing them with __.

How is this problem solved in practice? I probably don't have a
representative sample, but in the libraries that I have been using so
far, there were a lot of undocumented (in the sense of: not being part
of the public API) instance variables not prefixed with __. I have
therefore started to first grep the source of all base classes
whenever I introduce a new variable in my derived class. Is that
really the way it's supposed to be? What if one of the base classes
introduces a new variable at a later point?


Best,

   -Nikolaus

-- 
 »It is not worth an intelligent man's time to be in the majority.
  By definition, there are already enough people to do that.«
                                                         -J.H. Hardy

  PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6  02CF A9AD B7F8 AE4E 425C




More information about the Python-list mailing list