accessor/mutator functions

Steve Holden steve at holdenweb.com
Tue Mar 1 05:43:34 EST 2005


Carl Banks wrote:
> mirandacascade at yahoo.com wrote:
[...]

>>My questions are:
>>a) Are the three things above considered pythonic?
> 
> 
> No.  It's not good programming practice in C++, either.
> 
> If you have a class that's nothing but a big data structure, you ought
> to use it as a data structure.  Writing accessor and mutator methods
> for its fields is just doing a lot of work to accomplish nothing.
> 
Unfortunately Java has introduced this as a standard practice, and a lot 
of people who learned their programming by learning Java in the last ten 
years have absolutely no clue what a data structure *is*. (i.e. data, 
with a structure, but no logic required).

> If you want to provide access to a certain occasional field, but you're
> concerned about keeping the interface backwards-compatible, go ahead
> and use them.  But try to observe the following rules of thumb:
> 
> 1. Don't provide accessor or mutator function to every single member of
> every single class you write.  Only provide accessor/mutator functions
> if the accessor/mutator methods are a sensible and useful part of the
> class's interface.
> 
> 2. Don't think of these methods as accessors or mutators.  Instead,
> think
> of them as methods that access or mutate a certain abstract property of
> the object that happens to be represented by a single member.
> 
> And, keep in mind that, since Python doesn't really have private data,
> you don't have to worry about adding these functions to make debugging
> easier.
> 
> 
> 
>>b) What are the tradeoffs of using getattr() and setattr() rather
>> than creating accessor and mutator functions for each data member?
> 
> 
> Don't use getattr and setattr unless you have to construct the name of
> the attribute at run time.  That's what they're for.
> 
> 
Well, they are surely helpful in delegation contexts as well, or do I 
misunderstand?

regards
  Steve



More information about the Python-list mailing list