Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #79799 > unrolled thread
| Started by | Harvey Greenberg <hjgreenberg@gmail.com> |
|---|---|
| First post | 2014-10-27 11:23 -0700 |
| Last post | 2014-10-27 15:48 -0400 |
| Articles | 3 — 3 participants |
Back to article view | Back to comp.lang.python
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
| From | Harvey Greenberg <hjgreenberg@gmail.com> |
|---|---|
| Date | 2014-10-27 11:23 -0700 |
| Subject | variable attribute name |
| Message-ID | <6fc1feb3-651e-49e9-8a5d-66dc0599a754@googlegroups.com> |
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.
[toc] | [next] | [standalone]
| From | Larry Martell <larry.martell@gmail.com> |
|---|---|
| Date | 2014-10-27 14:32 -0400 |
| Message-ID | <mailman.15241.1414434766.18130.python-list@python.org> |
| In reply to | #79799 |
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)
[toc] | [prev] | [next] | [standalone]
| From | Ned Batchelder <ned@nedbatchelder.com> |
|---|---|
| Date | 2014-10-27 15:48 -0400 |
| Message-ID | <mailman.15242.1414439313.18130.python-list@python.org> |
| In reply to | #79799 |
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
[toc] | [prev] | [standalone]
Back to top | Article view | comp.lang.python
csiph-web