[Python Wpg] Swapping object attribute values
Stuart Williams
stuartw at mts.net
Thu Feb 26 09:38:12 EST 2009
Not knowing the context of your call to transpose, I wonder if instead
of writing
anObject.transpose('field1', 'field2')
why you wouldn't just write this:
anObject.field1, anObject.field2 = anObject.field2, anObject.field1
Stuart.
On Thu, Feb 26, 2009 at 7:15 AM, Sydney Weidman <syd at plug.ca> wrote:
> I like the way you can swap the values of variables in Python by saying
> something like:
>
> a, b = b, a
>
> but suppose I want a function that will swap arbitrary attributes on an
> object. Could I code that using the tuple unpacking assignment style? I
> ended up doing this:
>
> def transpose(self, from_attr, to_attr):
> """Transpose the co-ordinates from one axis to another"""
> to_val = getattr(self,to_attr)
> setattr(self, to_attr, getattr(self, from_attr))
> setattr(self, from_attr, to_val)
>
> Is there a more compact, readable way to do this?
>
> Regards,
> Syd
>
>
> _______________________________________________
> Winnipeg Python Users Group mailing list
> http://WinniPUG.ca
> Winnipeg at python.org
> http://mail.python.org/mailman/listinfo/winnipeg
>
More information about the Winnipeg
mailing list