2

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!

1 Answer 1

3

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")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.