1

I am trying to print out result1.key and result2.key by using the getattr. However I cannot get the last print function to work. I get the Error: NameError: name 'key' is not defined. How would I be able to make the print functions print(getattr(result1, key)) print(getattr(result2, key)) work to get the Expected Output?

results = ["result1", "result2"]
valuelist1 = [3, 5]
valuelist2 = [10, 6]

def func(val, val2):
    return val* val2 + val2/2

class Dummy:
    def __init__(self, val, val2):
        self.key = func(val, val2)

for counter, runs in enumerate(results):
    dummy = Dummy(valuelist1[counter], valuelist2[counter])
    globals()[runs] = dummy


print(result1.key)
print(result2.key)
for name in results:
    print(getattr(name, "key")) 

Expected output:

35.0
33.0
35.0
33.0
tony selcuk
  • 709
  • 3
  • 11

1 Answers1

0

You assign the Dummy instance to the globals(). So you need to access them in the same way, because name is only the string/name of your variable (in the global scope).

Do

for name in results:
    print(globals()[name].key)

or

for name in results:
    print(getattr(globals()[name], "key"))

or (but in general I wouldn't recommend to use eval(), only mentioned as another possible way for the sake of completeness)

for name in results:
    print(eval(name).key)
Sven Eberth
  • 3,057
  • 12
  • 24
  • 29