取决于变量的方法调用方式? [英] 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:
def read_A():
#doing sth
def read_B():
#doing sth else
def read_C():
等
现在,当字母('A'
,'B'
,'C'
,...)作为变量给出.
Now I would like to call those methods in a pythonic way, when the letter ('A'
, 'B'
, 'C'
, ...) is given as a variable.
一个非Python解决方案将是:
A non-pythonic solution would be:
if var == "A":
read_A()
if var == "B":
read_B() .....
我希望找到一个更Python化的解决方案,使我可以像这样简单地调用这些方法:
And I hope to find a more pythonic solution that allows me to call those methods simply like this:
var = "A"
read_var() #This would call the method 'read_A()'
请注意,上面的代码仅是我希望执行的操作的图像,而不是可行的示例!
Please mind that the code above is only an image of what I hope to do, it is not a working example!
推荐答案
我看不到仅使用一个问题
I dont see an issue with just using
if var == 'A':
read_a()
但是,如果您想使其更像"pythonic",则可以使用字典将变量映射到方法,并根据存储在字典中的结果执行它:
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:
def read_a():
print('Running method read_a')
def read_b():
print('Running method read_b')
switch = {'A': read_a, 'B': read_b}
case = 'A'
switch.get(case)()
>> 'Running method read_a'
case = 'B'
switch.get(case)()
>> 'Running method read_b'
这篇关于取决于变量的方法调用方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!