2

I have a program in which I'm trying to change a certain variable of a class depending on which one is designated earlier in the program. I want to know if I can indicate which variable I want to change by storing the variable name in another variable, is it possible?

Example:

class Vars:
    first = 0
    second = 0

variable_name = first

Vars.variable_name += 1

I want Vars.first to be equal to 1 after this code is executed, is this possible?

ZenenT
  • 45
  • 4
  • 2
    Sounds like an XY problem... what do you need this for? – RobertR Oct 27 '15 at 22:22
  • Possible duplicate of http://stackoverflow.com/questions/1373164/how-do-i-do-variable-variables-in-python. – RobertR Oct 27 '15 at 22:27
  • why do you want to do this? – Padraic Cunningham Oct 27 '15 at 22:29
  • It sounds like you may want a `dict` or even a `list` - there are not that many reasons to use a variable variable name especially if you are starting out with the language. – nneonneo Oct 27 '15 at 22:34
  • I have 4 timezones in a class and I need to assign and append values to each one through a loop. I have an if statement that determines which one to change, and then another function which determines the amount to change it by. – ZenenT Oct 27 '15 at 22:40

2 Answers2

2

Yeah, you can use getattr()/setattr() for that:

In [1]: class Vars:
   ...:     first = 0
   ...:     second = 0
   ...:

In [2]: variable_name = 'first'  # You have to change it to string since we don't know anything
                                 # about the `first` object outside of the class.

In [3]: old_value = getattr(Vars, variable_name)

In [4]: setattr(Vars, variable_name, old_value + 1)

In [5]: Vars.first
Out[5]: 1

You can also use the class' __dict__ object, but that's a bit dirty (and unpythonic) way:

In [1]: class Vars:
        first = 0
        second = 0
   ...:

In [2]: Vars.first
Out[2]: 0

In [3]: variable_name = 'first'

In [4]: Vars.__dict__[variable_name] += 1

In [5]: Vars.first
Out[5]: 1

In [6]: Vars.__dict__[variable_name] += 1

In [7]: Vars.first
Out[7]: 2
Igor Hatarist
  • 5,234
  • 2
  • 32
  • 45
  • Thanks for your response. One question: why shouldn't I use the __dict__ object? Shouldn't I use any available tools in a language to solve my problem? – ZenenT Oct 28 '15 at 15:00
1

There is a Python function called setattr which is used to set an attribute in an object.

You can store the variable name you want and change it like example below:

variable_name = "first"
setattr(Vars,variable_name,1)
Amir
  • 820
  • 9
  • 30