Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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"

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading