Why does python not have a mechanism for data hiding?

Russ P. Russ.Paielli at gmail.com
Tue Jun 3 00:38:07 EDT 2008


On Jun 2, 5:11 pm, Paul Rubin <http://phr...@NOSPAM.invalid> wrote:
> "Russ P." <Russ.Paie... at gmail.com> writes:
> > I also realize, by the way, that Python allows a client of a class to
> > define a new class member from completely outside the class
> > definition. Obviously, that cannot be declared private.
>
> This is bogus about 95% of the time though.  For the cases where it is
> really desired, I think it's best to require the target class to be
> enable it specifically somehow, maybe by inheriting from a special
> superclass.  That could let the compiler statically resolve member
> lookups the rest of the time.

It did seem a bit odd to me when I realized that you can add data
members (or even a "methods") to a class from completely outside the
class definition. That can be risky, of course, and as you suggest,
perhaps it shouldn't even be allowed by default.

I usually find that it's safer to initialize in the constructor all
(or nearly all) of the data members that will be needed in a class. If
I need a list that will be populated later, for example, I reserve the
name with an empty list in the constructor. Then, if for some reason
the list gets accessed before it is populated, I don't get an
exception.



More information about the Python-list mailing list