Class design: accessing "private" members

Alex Martelli alex at magenta.com
Mon Jul 3 05:07:43 EDT 2000


Frank V. Castellucci <frankc at colconsulting.com> wrote in message
news:395D79FE.4E4FDBCE at colconsulting.com...
> Jerome Quelin wrote:
> >
> > "Alex Martelli" <alex at magenta.com> wrote:
> > >By calling the accessors, rather than accessing the data
> > >directly, you ensure that if somebody overrides the
> > >accessor functions in a derived class you'll be calling
> > >the derived-class versions of those functions.  If that is
> > >what you want (one direction along which you want to let
> > >inheritors of your class extend or tweak behaviour), then
> > >it's probably worth the overhead you mention.
> > The class isn't to be derived any further. It's a class that I use in an
> > application, and that may be imported in some other applications, but
not to be
> > inherited.

Then, "do the simplest thing that could possibly work" applies.

> > Then, is it better/cleaner to access private members with accessors or
not?
> > Is it a matter of style? Or are there hidden caveheats using (or not
using)
> > accessors? It _seems_ cleaner to use accessors, but man, it's quite
awkward.

I would not use accessors that feel awkward to you, without specific
purpose.

> As you really have no way to "prohibit" further derivation (unless I
> missed the "final" keyword in the reference), using your accessors and
> praying that anyone over-riding the accessor/mutator methods does the
> proper thing would be my direction.

Such "prohibition" is not hard at all:

class dontderive:
    def __init__(self):
        if self.__class__ != dontderive:
            raise "told you not to!"

class foo(dontderive):
    pass

However, I wouldn't normally do it, again under the "simplest thing"
principle.  Just documenting "this class is not meant to be derived
from, so, just don't do it, or results will be unpredictable" is likely
to be "the simplest thing that could possibly work" in this case.


Alex






More information about the Python-list mailing list