简体   繁体   中英

Python - How to pass arguments with exec() method?

I would like to add methods in a class that have the same signature and trigger their call from a parent method like shown below. This example works:

class A:
    def call_others(self, settings):
        switch = {'add': self.action_add, 'remove': self.action_remove}
        for key in settings:
            switch[key](settings[key])
   
    def action_add(self, settings):
        pass

    def action_remove(self, settings):
        pass

But now I would like to create automatically the switch dict by retrieving the action functions and call them with exec like this:

class A:
    def call_others(self, settings):
        
        prefix = 'action_'
        actions = [func[len(prefix):] for func in dir(self) if func.startswith(prefix)]

        switch = dict()
        for action in actions:
            switch[action] = 'self.'+prefix+action

        for key in settings:
            exec(switch[key](settings[key]))
   
    def action_add(self, settings):
        pass

    def action_remove(self, settings):
        pass

In this example, exec(switch[key](settings[key])) does not work, exec expects a str and I can't see how to supply the settings[key] argument.

settings example is given here:

settings = {'add': [1, 2, 3, 4], 'remove': {'condition': True, 'number': 5}}

Thanks for your help!

You don't need exec .

for action in actions:
    switch[action] = getattr(self, prefix + action)

for key in settings:
    switch[key](settings[key])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM