-3

I'm have a class that has many different functions and I want to run all the functions with a loop

Some example code

class a:
    def one():
        return "one"
    
    def two():
        return "two"

b = ['one', 'two']

c = []
for i in b:
    c.append(exec("a." + i + "()"))

print(c)
# output: [None, None]

I want the output of a.i() to be concatenated to the variable c but it isn't working because exec is just running that part of code, it's not returning the output. How do I make it so I can store it in a variable?

Anonymous
  • 1
  • 1
  • Dont use exec, it is really bad practice. – matszwecja Jul 06 '22 at 23:02
  • 1
    You would need `eval` instead to get a result from the expression, keeping in mind that it will only work for an *expression* (no `if` statements, etc.) However, you should use more specific tools to access the information. Not to mention, the way that `class a:` is used in this code does not make sense. – Karl Knechtel Jul 06 '22 at 23:05
  • Just change it to `c.append(getattr(a, i)())` – tdelaney Jul 06 '22 at 23:13

1 Answers1

1

It's actually much simpler than that.

You don't have to define strings, and definitely don't use exec. Just use function pointers:

class a:
    def one():
        return "one"
    
    def two():
        return "two"

b = [a.one, a.two]

c = []
for i in b:
    c.append(i())

print(c)
# output: [one, two]
Daniel Trugman
  • 8,186
  • 20
  • 41