"Private" Member Variables

Hung Jung Lu hungjunglu at yahoo.com
Sun May 30 11:52:53 EDT 2004


Alan Gauld <alan.gauld at btinternet.com> wrote:
> 
> There is very rarely any good reason to provide getXXX/setXXX
> type accessor functions, even in C++ 
>

Accessor methods are often needed in simple-generic programming in
C++/Java/C#. (With the coming of actual generics in Java/C#,
accessors/properties will be even more common. C++ does get away a
little bit because it has weakly-typed templates.)

There is an asymmetry between data member and function members in
C++/Java/C#. Whereas in Python you have virtual data fields, in
C++/Java/C# you DON'T. You only have virtual functions.

This is a gigantic limitation. In Python, you write a parent class to
access child-class attributes all the time. In fact, you often use
statements like:

      if hasattr(self, 'tax'):
          self.total_price = self.price + self.tax

in the parent class, where the 'tax' attribute exists only for a
taxable child class.

Similarly, getters/setters are necessary in mix-in classes in Java/C#.
To me, one main reason for getters/setters is the lack of virtual data
fields. You NEED to use accessor methods to emulate virtual data
fields.

> Exposing your data via accessor functions is still exposing it 
> (albeit with control over read/write access). 

In C++/Java/C#, very often it's not a matter of choice, but a matter
of need. Without accessor methods, you have no way of writing generic
programs like:

(a) a parent class accessing data fields of a child class
(b) a mix-in class accessing data fields of the main class

(Mix-ins are achieved by containment plus possible delegation, that's
the way how multiple inheritance works in Java/C#).

regards,

Hung Jung



More information about the Python-list mailing list