[Tutor] Addressing a variable whose name is the value of a string
Andreas Pfrengle
spelzdinkelclonk at web.de
Mon Apr 9 18:18:29 CEST 2007
Kent Johnson wrote:
> Andreas Pfrengle wrote:
>
>> # Accessing db (see http://www.djangoproject.com/documentation/db-api/):
>> myobj = MyModel.objects.get(<some filter>)
>> var = myobj.vector
>> # vector is a Textfield, so var now contains a string, naming another
>> db-field of myobj
>>
>> execstr = "attr = myobj." + var
>> exec execstr
>> # attr now contains the content of the field named in var (an int in
>> my case)
>
>
> Use
> attr = getattr(myobj, var)
>
>> attr += 42 #some calculation with attr
>>
>> execstr = "myobj." + var + " = attr"
>> exec execstr
>
>
> setattr(myobj, var, attr)
>
> Kent
>
Thanks Kent, I've just looked up getattr and setattr, and since they
take strings for the addressed attributes, this really seems to be the
optimal solution! :)
More information about the Tutor
mailing list