Getters and Setters

Greg Ewing greg.ewing at compaq.com
Fri Jul 16 00:34:46 EDT 1999


Tim Peters wrote:
> 
> Python goes one better:  you can write an explicit method if needed, but it
> doesn't encourage bad practice by automatically supplying methods that
> expose every data attribute, crying "use me! abuse me!" <wink>.

There's something to be said for designing a
language so that the same syntax is used for
accessing an attribute whether it's directly
exposed or got at through a method.

I once designed a class system for Scheme
in which all instance variable access from
outside the object was through methods. For
instance variables declared as public, access
methods were automatically created. (There was
also a read-only category which got getters
only.)

The beauty of this was that I could start off
defining something as a directly accessible 
instance variable, and then later change my mind,
and not have to change any of the code which
used the object.

The moral of this is that it's a good idea to
always use accessor methods from outside the
object, and thus having a way of generating
them automatically would be useful.

To avoid inadvertently exposing everything,
they should only be generated for attributes
somehow marked as public or read-only.

I think that instead of being completely
automatic it should be something you explicitly
request when defining the class, e.g.

  class Foo:
    blarg = 0
    parrot = ""

  define_public(Foo, 'blarg')
  define_read_only(Foo, 'parrot')

Implementations of these two functions left
as an exercise...

Greg




More information about the Python-list mailing list