Standard behaviour of a getSomething method

Stefan Schwarzer sschwarzer at sschwarzer.net
Sat Jul 26 15:46:47 EDT 2003


Mike Rovner wrote:
> Batista, Facundo wrote:
> 
>> When I want to know about a attribute (e.g.: myAttrib) of an object, I
>> should use the specific method (e.g.: getMyAttrib).
> 
> Python don't enforce nor encourage attribute hiding,
> so don't do it unless you have a good reason.
> Plain access to attributes is simple:
>     myObject.myAttribute

I think, you should hide an attribute if it doesn't refer to the
object's abstract interface but instead merely depends on the
implementation. In that case, you shouldn't provide any means to
access the attribute directly, be it via direct attribute access or
accessor methods.

Somewhat, I dislike the sometimes recommended __getattr__/__setattr__
approach. I wouldn't like to have something like

def __getattr__(self, name):
     if name == '...':
         ...
     elif name == '...':
         ...
     ...
     else:
         raise AttributeError("%s has no attribute %s" % (self.__class__, name))

but prefer modifying only the corresponding get/set method(s).

But, if I had lots of get/set methods, I would surely use the
__getattr__/__setattr__ approach or generate the get/set methods
"automatically", with a function like

make_accessors.make_accessors(cls, "foo bar baz spam eggs")

which would generate

def foo(self):
     return self._foo

def set_foo(self, new_foo):
     self._foo = new_foo

and the other accessor methods, if they are not yet defined otherwise.
This can be done easily with Python.

In one project, we use a similar method to generate accessor methods
for persistent objects to be stored in a database. Here, the accessors
(which correspond to the "public" database columns in a table row) are
a bit more complicated.

>> Considering that this attribute is always another object (everything
>> is an object in Python), what should getMyAttrib do?
>>
>> 1) Return the object
>> 2) Return a copy of the object

Because returning a copy is seldom needed, I prefer returning the
object itself. If it's an immutable object, the difference doesn't
matter, anyway. If it's a mutable object, you should note the access
semantics in the docstring, as someone else pointed out.

Stefan





More information about the Python-list mailing list