use str as variable name

Cameron Laird claird at lairds.us
Thu Sep 4 08:02:08 EDT 2008


In article <48bf9d12$0$7552$426a74cc at news.free.fr>,
Bruno Desthuilliers  <bruno.42.desthuilliers at websiteburo.invalid> wrote:
>Mathieu Prevot a écrit :
>> 2008/9/4 Chris Rebert <cvrebert at gmail.com>:
>
>(snip)
>
>>> You're looking for the setattr() built-in function. In this exact case:
>>>    setattr(a, arg, new_value)
>>>
>>> This is probably covered in the Python tutorial, please read it.
>>>
>>> Regards,
>>> Chris
>> 
>> Indeed.
>> 
>> I'll use:
>> a.__setattr__(height, new_value)
>
>Please don't. Use the generic setattr() function instead. This holds for 
>any __magic__ method : they are *implementation* for operators and 
>generic functions  - which you can think of as operators with a function 
>syntax -, and are not meant to be called directly. You wouldn't write 
>something like 2.__add__(3), would you ?
>

Along with the good advice the usual suspects have given,
my intuition is that there's an even better implementation
that doesn't setattr() at all.  While it's impossible to
know, of course, because we don't have the original poster's
true requirements, I conjecture that, rather than "to link
this [user-supplied] word to a class variable", what will
serve him best is to regard the user text as an index into
a class dictionary.



More information about the Python-list mailing list