Standard behaviour of a getSomething method

Asun Friere afriere at yahoo.co.uk
Wed Jul 23 23:32:54 EDT 2003


"Batista, Facundo" <FBatista at uniFON.com.ar> wrote in message news:<mailman.1058966922.4133.python-list at python.org>...
> When I want to know about a attribute (e.g.: myAttrib) of an object, I
> should use the specific method (e.g.: getMyAttrib).
> 
> Considering that this attribute is always another object (everything is 
> an object in Python), what should getMyAttrib do?

Given that your method is called 'get*' and not 'copy*', my feeling is
that an accessor method should in general return the object itself.  A
client programmer might be surprised if they 'got' a mutable object,
changed it, but it did not change at all.  As has been pointed out,
either way, documenting what it does is essential.

However, while the importance of accessing attributes only via such
'accessor methods' is sometimes stressed, it appears to be more
pythonic to access attributes directly. (ie just use myobj.myAttrib) 
The ususal critique, -- namely that direct access increases the
'coupling' between object, making it difficult to alter the
implementation of an object without altering its public interface --
is met in Python by the use of python properties (which allow the
wrapping of what, to client code, looks  like direct attribute
access.)  At least that is how I have (recently) quelled my unease
about direct attribute access. (My older code is still filled with
get* and set* methods for all sorts of attributes which usually do
nothing more than 'return self.attribute')

The advantage of doing it that way is faster (you save method calls),
more readible code.




More information about the Python-list mailing list