use member functions to access data in Python classes?

Alex Martelli aleax at
Wed Jun 18 22:09:48 CEST 2003

Peter Hansen wrote:

> beliavsky at 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?
> I follow the conventional approach used even by the Python libraries,
> which have proven to be quite effective :-), by just accessing most
> data directly.
> If the type of access involved is more complicated that getting or
> setting, I naturally provide a method to perform the operation
> instead.
> Note that the latest versions of Python have "properties" which will
> allow you to combine the best (?) of both worlds by writing code as
> though it had direct access but which actually calls methods under
> the table.

Note further that you could obtain the same effect with custom
__getattr__ and __setattr__ methods even in stone-age Python --
the introduction of properties is quite welcome because it makes
this style handier and faster, but it's not the _enabler_ of it.

By 'this style' I mean: access attributes as attributes.  If in
the future the attribute needs to go away as such and rather
get computed at need, and/or setting the attribute needs to cause
some other changes to keep some new class-invariant, then turn
the attribute into a property -- client-code stays unchanged,
never having to deal with the extra syntax boilerplate required
by explicitly calling getter/setter methods, so, no problem!


More information about the Python-list mailing list