Class design: accessing "private" members

Jake Speed speed at ?.com
Fri Jun 30 15:00:59 EDT 2000


jerome.quelin at insalien.org (Jerome Quelin) wrote in
<962367319.379353174 at news.libertysurf.fr>: 

>Then, is it better/cleaner to access private members with accessors or
>not? Is it a matter of style? Or are there hidden caveheats using (or
>not using) accessors? It _seems_ cleaner to use accessors, but man, it's
>quite awkward. 

The usual trick is to write __getattr__ / __setattr__ methods.

Here's a class that'll try to call 'get_var' for
any undefined field 'var', and 'set_var' whenever
set_var exists:

class Object:
    def __getattr__(self, name):
        try:
                return getattr(self.__class__, "get_" + name)(self, name)
        except AttributeError:
                raise AttributeError, name
    def __setattr__(self, name, value):
        try: 
            getattr(self.__class__, "set_" + name)(self, name, value)
        except AttributeError:
            self.__dict__[name] = value

    def get_x(self, name):
        return self.__x
    def set_x(self, name, value):
        self.__x= value

obj = Object()
obj.x = 2
print "obj.x =", obj.x
print "obj.__dict__ =", obj.__dict__;

and voila, whenever your program calls 'obj.x = val', your
class calls 'set_x', which acesses its private field __x --
and does whatever else it needs to do.  

I think JPython uses JavaBeans this way, so you can write
'window.Background = Color.blue', and it calls 
'window.setBackground(Color.blue)' which might generate a
redraw event or something.

-Speed!



More information about the Python-list mailing list