Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Standard behaviour of a getSomething method

1 view
Skip to first unread message

Batista, Facundo

unread,
Jul 23, 2003, 9:17:27 AM7/23/03
to

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?

        1) Return the object
        2) Return a copy of the object

How do I return a copy of the object?

Thanks for all.

.       Facundo





. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

ADVERTENCIA 

La información contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener información confidencial o propietaria, cuya divulgación es sancionada por la ley.

Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no está autorizado a divulgar, copiar, distribuir o retener información (o parte de ella) contenida en este mensaje. Por favor notifíquenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magnético) que pueda haber realizado del mismo.

Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telefónica Comunicaciones Personales S.A. o alguna empresa asociada.

Los mensajes electrónicos pueden ser alterados, motivo por el cual Telefónica Comunicaciones Personales S.A. no aceptará ninguna obligación cualquiera sea el resultante de este mensaje.

Muchas Gracias.

Lee Harr

unread,
Jul 23, 2003, 5:13:48 PM7/23/03
to
In article <mailman.105896692...@python.org>, Batista, Facundo:
> This message is in MIME format. Since your mail reader does not understand
> this format, some or all of this message may not be legible.
>

> 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?
>
> 1) Return the object
> 2) Return a copy of the object
>

I do not think there is a definite rule regarding this. However,
whichever one it does, you should probably document it :o)

> How do I return a copy of the object?
>

You can use the copy module to create either a shallow or deep copy.


Dan Williams

unread,
Jul 23, 2003, 7:19:52 PM7/23/03
to
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).
>
Its not really considered "pythonic" to access attributes through
getters and setters. Instead, you can access them directly:

>>> class Foo:
... def __init__(self, val):
... self.a = val
...
>>> foo = Foo(4)
>>> print foo.a
4
>>> foo.a = 6
>>> print foo.a
6
>>>

If you need to to other processing of the data for the data (ie, if you
wanted to give a copy), you can use the __getattr__ and __setattr__
methods.

> 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
>
> How do I return a copy of the object?

try looking at:
>>> import copy
>>> help(copy)

HTH,
-Dan

>
> Thanks for all.
>
> . Facundo
>
>

[snip]

Asun Friere

unread,
Jul 23, 2003, 11:32:54 PM7/23/03
to
"Batista, Facundo" <FBat...@uniFON.com.ar> wrote in message news:<mailman.105896692...@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.

Batista, Facundo

unread,
Jul 24, 2003, 5:09:53 PM7/24/03
to
Resending... get no answers, don't remember if this mail reached the list.


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?

1) Return the object


2) Return a copy of the object

How do I return a copy of the object?

Thanks for all.

. Facundo

Ben Finney

unread,
Jul 24, 2003, 6:22:52 PM7/24/03
to
On Thu, 24 Jul 2003 18:09:53 -0300, Batista, Facundo wrote:
> Resending... get no answers, don't remember if this mail reached the
> list.

It reached the newsgroup, and discussion ensued.

<http://groups.google.com/groups?threadm=38ec68a6.0307231932.7a7f53eb%40posting.google.com>

--
\ "Too many pieces of music finish too long after the end." -- |
`\ Igor Stravinskey |
_o__) |
http://bignose.squidly.org/ 9CFE12B0 791A4267 887F520C B7AC2E51 BD41714B

Mike Rovner

unread,
Jul 24, 2003, 5:56:24 PM7/24/03
to
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

> 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

Usualy statement
x=y
creates a new object y referencing to old object y.
If y allows modification it can be modified through name 'x'
If you want a copy:

> How do I return a copy of the object?

Do it explicitly:
myObject.copy()
or
import copy
copy.copy(myObject)
copy.deepcopy(myObject)

Mike


Jp Calderone

unread,
Jul 24, 2003, 9:08:11 PM7/24/03
to
On Thu, Jul 24, 2003 at 02:56:24PM -0700, Mike Rovner wrote:
> Batista, Facundo wrote:
>
> [snip]

>
> Usualy statement
> x=y
> creates a new object y referencing to old object y.

Neither `x' nor `y' above are objects. Hence, the statement does not
create a new object.

What it does do is create a new binding (`x') to an object which already
exist (referenced by `y').

Jp

--
"Pascal is Pascal is Pascal is dog meat."
-- M. Devine and P. Larson, Computer Science 340

Stefan Schwarzer

unread,
Jul 26, 2003, 3:46:47 PM7/26/03
to
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

John Roth

unread,
Jul 26, 2003, 6:15:17 PM7/26/03
to

"Stefan Schwarzer" <sschw...@sschwarzer.net> wrote in message
news:bfulr8$5mi$1...@online.de...

> 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.

I agree with the general principle: implementation details shouldn't
be generally availible in the same way as the public API.

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

That sounds more than a bit heavyhanded to me. The more
general practice is simply to name private attributes with a
leading underscore. Then you can verify that there aren't any
improper references by scanning the source for references to
underscored variables that don't start with "self._".

John Roth


Stefan Schwarzer

unread,
Jul 26, 2003, 8:00:46 PM7/26/03
to
John Roth wrote:
> "Stefan Schwarzer" <sschw...@sschwarzer.net> wrote in message
> news:bfulr8$5mi$1...@online.de...
>> Somewhat, I dislike the sometimes recommended __getattr__/__setattr__
>> approach. I wouldn't like to have something like
>
> That sounds more than a bit heavyhanded to me. The more
> general practice is simply to name private attributes with a
> leading underscore. Then you can verify that there aren't any
> improper references by scanning the source for references to
> underscored variables that don't start with "self._".

I refered to public attributes here. For private (i. e. implementation-
specific) attributes I would just use the leading-underscore convention,
like you.

Stefan

Batista, Facundo

unread,
Jul 28, 2003, 9:52:31 AM7/28/03
to
#- >> 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.

Here it's the very point. I don't want to anybody to access the class
attribute from outside.

Beyond the get/set interface mechanism, if I return the object (a mutable
one), this object can be modified from outside. Shouldn't I return a copy of
the object in this case?

Thanks.

. Facundo

0 new messages