-1

How can I call multiple class' methods with a for loop in python? Also, How do I fix the AttributeError so that when I have many more methods, I don't have to write conditional statements to call every method one by one? My code is as follows. Thanks

class Test:
    def __init__(self):

    def method_1(self, key):

    def method_2(self, key):

    def method_3(self):

def process(commands):
    length = len(commands)
    result = []
    stack = Test()

    for command in commands:
        command = command.split()
        if len(command) == 2:
            # Perform stack.method_1 or stack.method_2
            result.append(stack.command[0](command[1])) <====== AttributeError
        else: 
            # Perform stack.method_3
            result.append(stack.command) <===== stack has no attribute command
    return result

commands = ["method_1 5","method_2 9", "method_3", "method_1 2"]

1 Answers1

0

use getattr function to access the attribute value of an object

for command in commands:
    command = command.split()

    if len(command) == 2:
        # Perform stack.method_1 or stack.method_2
        result.append(getattr(stack, command[0])(command[1]))
    else:
        # Perform stack.method_3
        result.append(getattr(stack, command[0])())
return result

What is getattr() exactly and how do I use it?

sushanth
  • 8,275
  • 3
  • 17
  • 28