use member functions to access data in Python classes?

Aahz aahz at pythoncraft.com
Wed Jun 18 12:40:45 EDT 2003


In article <3064b51d.0306180815.75869d6f at posting.google.com>,
 <beliavsky at aol.com> wrote:
>
>In C++, it is generally recommended to declare the data within a class
>private and to access the data using member functions. Do experienced
>Python programmers usually use member functions to access data within
>classes, or do they access the data directly?

"It depends".  Generally speaking, though, most Python classes manage
data attributes without accessor functions.  If you later discover that
you were wrong, you can always keep the interface, switch to new-style
classes (if you haven't already done so), and make the attribute a
property instead.

One thing Pythonistas *don't* do is use accessor functions to keep a
data attribute private.  Because of Python's introspection capabilities,
there's essentially no true privacy protection, so you only use accessor
functions when you want to document that code is needed to manipulate an
attribute.
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

"If you don't know what your program is supposed to do, you'd better not
start writing it."  --Dijkstra




More information about the Python-list mailing list