0

I want to use a variable to access an attribute of an object created by a class, but Python uses the variable's name as a the object's name and not the name stored in the variable.

class button():
    def __init__(self, color, x, y, width, height, text=''):
        self.color = color
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.text = text

white = (255,255,255).

A1 = button(white, 50, 50, 20, 20, text='Hello World')


var = "A1"

print(var.text)

And when I run it:


AttributeError: 'str' object has no attribute 'text'

Is there any way to use the information inside var as the object name when calling var.text?

Noah Leuthold
  • 65
  • 1
  • 4
  • 2
    Does this answer your question? [How do I create variable variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-variable-variables) – luk2302 Jan 03 '22 at 18:15
  • 2
    Variable names are for the benefit of the coder, not the code itself. If your code needs a variable name, it means you should be using a `dict`. – chepner Jan 03 '22 at 18:17
  • should be avoided - but `print(eval(var).text)` also works. – Robin Dillen Jan 03 '22 at 18:20
  • 1
    Any time you think `Variable variables` think `dict` (or in other languages, associative arrays). Any other way of implementing this with workarounds or ghastly `php`-like nonsense is going to cause a mess and possibly your life when the next developer sees your code. – JNevill Jan 03 '22 at 18:21

1 Answers1

-1

You can do it like this:

class button():
    def __init__(self, color, x, y, width, height, text=''):
        self.color = color
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.text = text

white = (255,255,255)

A1 = button(white, 50, 50, 20, 20, text='Hello World')


var = "A1"

print(locals()[var].text)
Eli Harold
  • 2,280
  • 1
  • 3
  • 22