use member functions to access data in Python classes?
Bengt Richter
bokr at oz.net
Thu Jun 19 16:51:04 EDT 2003
On 18 Jun 2003 09:15:15 -0700, 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?
As others have mentioned, probably mostly directly, and not for privacy
purposes. But sometimes it can be handy to make use of keyword args to
set or update a dict-type attribute. E.g.,
x.d = {'a':1, 'b':'two'}
can be spelled
x.set_d(a=1, b='two')
if x's class has the method
def set_d(self, **d):
self.d = d
Of course a little function
def mkd(**kw): return kw
will allow you to write
x.d = mkd(a=1, b='two')
and preserve the option to change d smoothly to a property later,
which might be a better choice sometimes.
Regards,
Bengt Richter
More information about the Python-list
mailing list