Why does python not have a mechanism for data hiding?
larry.bates at websafe.com`
Thu Jun 5 21:50:24 CEST 2008
Russ P. wrote:
> 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
That is EXACTLY when I want an exception, I did something that shouldn't happen.
You also are missing the nice ability of python to use hasattr() to find out
if a class instance has a method/attribute. I use hasattr() to test for
presence or absence of methods/attributes quite a lot. In the past I did what
you describe, but found that to be limiting and a throwback to when I used
languages that could not do introspection. I can test to see if the attribute
exists, if it is empty, which can be two very different conditions that require
two different actions. The only way you can do that is to initialize it to
None. While this works it is a fictitious construct that we all learned when we
were writing Fortran, Basic or Cobol years ago (oops I think I just revealed
that I'm an 'old timer'). Now I just do: if hasattr(self, 'listInQuestion') and
I can tell if it has been created (either by constructor) or by some other
method. This works particularly well when I do caching of data in objects that
are shared among methods. I can also do hasattr(object, 'methodInQuestion') to
see if the object implements an interface that I require.
May be a little off topic, but I think it is relevant.
More information about the Python-list