Variables from variables

Jeff Shannon jeff at ccvcorp.com
Fri Aug 17 20:02:31 CEST 2001


paul at nlhas.no wrote:

> I've come to a dead end with this one, and would be grateful for
> suggestions. Scenario - a tuple with field names (self.description) to
> be mapped to class variables and assigned values from self.record.
>
> I've got this far, and get the partially successful result shown
> below. I can't fathom the reasons for the exceptions.
>
> Is there an easier way to do this?
>

Yes.

>>> fields ={ 'one':1, 'two':2, 'three':3 }

>>> class Record:
...     def __init__(self, fielddict):
...         for name, val in fielddict:
...             setattr(self, name, val)
...
>>> r = Record(fields)

>>> print r.one, r.two, r.three
1 2 3

(Note: this is simulated, not tested, but I'm fairly confident I've got it
right.  The key is the setattr() call.)

Jeff Shannon
Technician/Programmer
Credit International





More information about the Python-list mailing list