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?

5
  • 2
    Sounds like an XY problem... what do you need this for? Commented Oct 27, 2015 at 22:22
  • Possible duplicate of stackoverflow.com/questions/1373164/…. Commented Oct 27, 2015 at 22:27
  • why do you want to do this? Commented Oct 27, 2015 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. Commented Oct 27, 2015 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. Commented Oct 27, 2015 at 22:40

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

1 Comment

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?
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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.