0

I'm trying to assign class variables at runtime based on key/value pairs in a dictionary, where the key is what is called, and the value refers to the variable to be set.

keys = {'hours':'hours', 'minutes':'minutes'}
hours = 0
minutes = 0

def set_time(self, key, value):
    self.keys[key] = value

set_time, will not be a simple setter, but will take value as a string and convert it to integer minutes or hours. I want to look up the correct variable name based on the key parameter, but this code changes the value of the dictionary entry instead. Tried to search google and SO, but don't know the words to describe what I'm trying to find.

nexus_2006
  • 744
  • 2
  • 14
  • 29
  • 1
    You're probably looking for [`setattr`](https://docs.python.org/2.7/library/functions.html#setattr). – BrenBarn Aug 03 '14 at 21:25
  • possible duplicate of [Using a string variable as a variable name](http://stackoverflow.com/questions/11553721/using-a-string-variable-as-a-variable-name) – merlin2011 Aug 03 '14 at 21:26
  • That is **not** how Python names work. I suggest you read [this](http://nedbatchelder.com/text/names.html). – jonrsharpe Aug 03 '14 at 21:26

1 Answers1

1

Have you tried using Python's setattr method?

For example,

setattr(x, 'minutes', 40)

is the same as writing

x.minutes = 40