Class design: accessing "private" members

Alex Martelli alex at magenta.com
Fri Jun 30 07:02:40 EDT 2000


Jerome Quelin <jerome.quelin at insalien.org> wrote in message
news:962352843.1667731268 at news.libertysurf.fr...
> Hi all,
>
> When designing a class, I wrote some accessors (get_var() and set_var()
> methods) for my "private" members (private in the sense that I don't want
> somebody to access them directly from outside the class.
> I was wondering if it is good practice to acceed to those private members
from
> _inside_ my class, or should I use the accessors methods too?
> Well, ok, it would be slower (function calls are always more expensive),
but
> isn't it more OO-well-behaviored?
>
> -- File test.py
> class Spam:
>     def __init__(self, name="eggs"):
>         self.set_name(name)  # Which is the
>         self._name = name    # better/cleaner?
>     def set_name(self, name):
>         self._name = name
> -- End of file

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.  But if you
need to ensure that the actual data gets modified and/or
updated, then beware...!


Alex






More information about the Python-list mailing list