Yehoshaphat Schellekens
Yehoshaphat Schellekens

Reputation: 2385

Apply method in instance according to a list python

I have a list (strings) of methods that I would like to apply on an instance (assuming they exist) as following:

class PrintStuff:
    
    def __init__(self):
        self.name = 'hi'

    def do_a(self):
        print(f'{self.name} a')

    def do_b(self):
        print(f'{self.name} b')

    def do_c(self):
        print(f'{self.name} c')

list_of_methods_to_activate = ['do_a', 'do_b']

ps = PrintStuff()

for dewsired_method_to_activate in list_of_methods_to_activate:
    #activate dewsired_method_to_activate in ps
    ps.dewsired_method_to_activate() #would like that to work

How can I invoke these methods, using a list

Any help on that would be awesome!

Upvotes: 2

Views: 33

Answers (1)

sushanth
sushanth

Reputation: 8302

try this, using getattr

list_of_methods_to_activate = ['do_a', 'do_b']

ps = PrintStuff()

for method in list_of_methods_to_activate:
    if hasattr(ps, method): # check's if method exists before calling
        getattr(ps, method)()
    else:
        print(f"{method} does not exists")

Upvotes: 3

Related Questions