0

Say have a simple class as follows:

class Test:
    some_attributes

    def first_method():
        pass

    def second_method():
        pass

Now lets say I have put the list of methods in a list like so: methods=['first_method', 'second_method']

The question that has perplexed me is:‌ How can I‌ call the methods using the list above in a for loop. The scheme I want is like this:

for method in methods:
    Test.method

I have tried:

for method in methods:
    'Test.{}'.formats(method)

and

for method in methods:
    vars()['Test.{}'.formats(method)]

How can I achieve this concept?

Amir Afianian
  • 2,679
  • 4
  • 22
  • 46

1 Answers1

0

You can use the getattr Python method, to call methods by name:

class Test:

    def first_method(self):
        print("1")

    def second_method(self):
        print("2")


test = Test()

methods=['first_method', 'second_method']

for method in methods:
    getattr(test, method)()
tituszban
  • 4,797
  • 2
  • 19
  • 30