Skip to content
Advertisement

Way to call method depending on variable?

I already have a working, but in my oppinion not beautiful solution for a part of a long script.

My script uses several similar methods, that differ too much to combine. However I came to a point where I want to call one of those methods depending on a given variable.

The names of the methods are build up like this:

JavaScript

etc.

Now I would like to call those methods in a pythonic way, when the letter ('A', 'B', 'C', …) is given as a variable.

A non-pythonic solution would be:

JavaScript

And I hope to find a more pythonic solution that allows me to call those methods simply like this:

JavaScript

Please mind that the code above is only an image of what I hope to do, it is not a working example!

Advertisement

Answer

I dont see an issue with just using

JavaScript

but if you’d like to make it more ‘pythonic’ you could map your variables to the methods using a dictionary and execute it based on the result of what’s stored in your dictionary:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement