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.
> 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.
>>> 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]
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.
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
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
> 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
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
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
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
I refered to public attributes here. For private (i. e. implementation-
specific) attributes I would just use the leading-underscore convention,
like you.
Stefan
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