Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #79802

Re: variable attribute name

From Ned Batchelder <ned@nedbatchelder.com>
Subject Re: variable attribute name
Date 2014-10-27 15:48 -0400
References <6fc1feb3-651e-49e9-8a5d-66dc0599a754@googlegroups.com> <CACwCsY7Sbgb-up5-0us3bYxfcvr-RQ6oQ-m+qDJyaLtAURfrOw@mail.gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.15242.1414439313.18130.python-list@python.org> (permalink)

Show all headers | View raw


On 10/27/14 2:32 PM, Larry Martell wrote:
> On Mon, Oct 27, 2014 at 2:23 PM, Harvey Greenberg <hjgreenberg@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

Back to comp.lang.python | Previous | Next — Previous in thread | Find similar | Unroll thread


Thread

variable attribute name Harvey Greenberg <hjgreenberg@gmail.com> - 2014-10-27 11:23 -0700
  Re: variable attribute name Larry Martell <larry.martell@gmail.com> - 2014-10-27 14:32 -0400
  Re: variable attribute name Ned Batchelder <ned@nedbatchelder.com> - 2014-10-27 15:48 -0400

csiph-web