Search code examples
pythonlistobjectattributesinstance

How to access an attribute of an instance having the name of this instance in a string


I have a list with all the names (strings) of the instances from a same class. I want to go through that list using a for loop and change their attributes one by one, but it raises this error: AttributeError: 'str' object has no attribute 'fixedColor'

Should I create another list containing the objects instead of strings, or is there a way to access them having the string object?

I want to apply it here:

listaCartas_temp = listaCartas
listaColores_temp = listaColores

for i in listaCartas:

    a=random.choice(listaCartas_temp)
    listaCartas_temp.remove(a)
    b=random.choice(listaCartas_temp)
    listaCartas_temp.remove(b)
    color = random.choice(listaColores_temp)
    listaColores_temp.remove(color)

    pairs.append(tuple([a, b]))

    a.fixedColor = color
    b.fixedColor = color

Where listaCartas (and listaCartas_temp) is a list containing those strings. I have various cards (cartas). I want to make unique pairs and assign a color to each pair.


Solution

  • you can use a dictionary to match relevant string to the specified value

    fixedColor = {}
    fixedColor[a] = color
    fixedColor[b] = color
    

    when you want to access the color simply do

    xxx = fixedColor[b]
    

    and it will just be the same as calling your "b.fixedColor"