1

This is probably a really novice question, so forgive me.

If I know the name of an instance/variable - let's say I have a string called "variable_name" and a variable with the same name, how would I go about writing a piece of code that takes that string and converts it into something I can actually use and use class methods on, etc? Is that a thing that can happen at all?

Edit: Added some code to better articulate my question. I've got a code setup kind of like this (simplified for space):

class Class_Name:
   count = 0

   def __init__(self, foo, bar):
        self.__class__.count += 1
        self.foo = foo
        self.bar = bar

def find_variable_name(class_name, number):
   variable_name = "variable" + str(number)
   return variable_name

variable1 = Class_Name("foo", "bar")
variable2 = Class_Name("foo2", "bar2")
variable3 = Class_Name("foo3", "bar3")

for instances in range(Class_Name.count):
   print (find_variable_name(Class_Name, instances+1).foo)

This would give me the error "AttributeError: 'str' object has no attribute 'foo'" - how would I turn the object from a string to something I can work with?

eyeofcod
  • 13
  • 3

2 Answers2

1

You can simply use exec() function:

k = "my_str"           # a string
exec(k +  " = k")      # my_str = "my_str"

Then, the output is:

>>> print(my_str)
'my_str'

The exec() function executes the string given it.
So, when we do exec(k + " = k"), it means, exec("my_str = k"), which assigns the value of the variable k to my_str.
This makes my_str = "my_str".

NOTE:
Be a little wary of the exec() function, especially if the value of the variable is user-inputted. Then, it could be dangerous to use.

CoolCoder
  • 786
  • 7
  • 20
0

locals() returns a dictionary of the variable bindings of the current scope.

The keys of the dictionary are strs so you can do lookup using the variable name. E.g.

>>> somevariable = 1
>>> locals()["somevariable"]
1

Of course it may be that the variable you want is not in the current scope, then it will not be in locals(). However, if it is in the global scope, you can use globals() in the same way. E.g.

>>> somevariable = 1
>>> globals()["somevariable"]
1

So in your example above, you might use a function like:

def find_variable_name(number):
    return globals()["variable" + str(number)]

Which you can use as:

>>> variable1 = Class_Name("foo", "bar")
>>> find_variable_name(1).foo
'foo'

NOTE THAT this type of thing is not good programming practice. Doing this makes code harder to read and understand and maintain. Depending on your application, it might be better just to keep a Dict of your objects, indexing with the counts. E.g.

>>> d = {i: Class_Name("foo", "bar") for i in range(10)}
>>> d[1].foo
'foo'
L.Grozinger
  • 2,280
  • 1
  • 11
  • 22