variable attribute name

Ned Batchelder ned at nedbatchelder.com
Mon Oct 27 15:48:31 EDT 2014


On 10/27/14 2:32 PM, Larry Martell wrote:
> On Mon, Oct 27, 2014 at 2:23 PM, Harvey Greenberg <hjgreenberg at gmail.com> wrote:
>> I want to let the name of an attribute be the string value of a variable.  Here is some code:
>>
>> class Object(object): pass
>> A = Object()
>> s = 'attr'
>> A.<s> = 1
>>
>> The last line denotes the variable value by <s> (not a python form).  What I want is to have A.attr = 1, but 'attr' determined by the value of s.  Please advise.
>
> setattr(A, s, 1)
>

Larry's code will work for you.  If you are making many attributes like 
this, you might be better off just using a dictionary in the first place:

     a = {}
     a[s] = 1


-- 
Ned Batchelder, http://nedbatchelder.com




More information about the Python-list mailing list