accessor/mutator functions

Nick Craig-Wood nick at craig-wood.com
Mon Feb 28 05:30:03 EST 2005


Michael Spencer <mahs at telcopartners.com> wrote:
>  mirandacascade at yahoo.com wrote:
> > When I look at how classes are set up in other languages (e.g. C++), I
> > often observe the following patterns:
> > 1) for each data member, the class will have an accessor member
> > function (a Get<whatever> function)
> > 2) for each data member, the class will have a mutator member function
> > (a Set<whatver> function)
> > 3) data members are never referenced directly; they are always
> > referenced with the accessor and mutator functions
> > 
> > My questions are:
> > a) Are the three things above considered pythonic?
> 
>  No
> 
> > b) What are the tradeoffs of using getattr() and setattr() rather than
> > creating accessor and mutator functions for each data member?
> 
>  Use property descriptors instead:
>  http://www.python.org/2.2.1/descrintro.html#property
>  http://users.rcn.com/python/download/Descriptor.htm#properties

Actually I would say just access the attribute directly for both get
and set, until it needs to do something special in which case use
property().

The reason why people fill their code up with boiler plate get/set
methods is to give them the flexibility to change the implementation
without having to change any of the users.  In python you just swap
from direct attribute access to using property().

Also note that with property() you can make an attribute read only (by
defining only the get method) which is often the encapsulation you
really want - and that is something you can't do in C++.

-- 
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick



More information about the Python-list mailing list