[英]Call either of two different functions based on a variable
I have two different functions cd_0
and cd_90
which return a floating point variable.我有两个不同的函数
cd_0
和cd_90
返回一个浮点变量。 I am using curve_fit
function in which I call either one of these function.我正在使用
curve_fit
function,其中我调用其中一个function。 I want to call either one of these functions using an var
value ( cd_<var>
) which can be either 0 or 90. The var
value is known at the beginning of the program and does not get modified.我想使用可以是 0 或 90 的
var
值 ( cd_<var>
) 调用这些函数中的任何一个var
值在程序开始时是已知的,并且不会被修改。 This being the case, I do not want to introduce a if
check since it will slow down the optimization function calling these either of two functions.在这种情况下,我不想引入
if
检查,因为它会减慢调用这两个函数之一的优化 function。 How to achieve this?如何做到这一点?
cd_func = cd_0 if var == 0 else cd_90
Later, when you want to call the chosen function:稍后,当您要调用所选的 function 时:
my_float = cd_func()
Note that a dict will also solve the problem, but you still make a check on every reference.请注意,dict 也可以解决问题,但您仍然要检查每个引用。 It's faster than your original
if
, but slower than the direct reference of cd_func
.它比你原来的
if
快,但比cd_func
的直接引用慢。
While not too elegant, you can actually use a dictionary for this.虽然不太优雅,但您实际上可以为此使用字典。
methods = {'cd_0': cd_0, 'cd_90', cd_90}
method_name = f'cd_{var}' # use f-strings since you know var
# to call
methods[method_name]()
There are multiple approaches to this that you can try, I will list some that are on the top of my head and choose what suits you.您可以尝试多种方法,我将列出一些在我脑海中的方法并选择适合您的方法。
eval
function.eval
function。 Python's eval
would run a string
as Python syntax. Python 的
eval
将以Python语法运行string
。 Example: eval("cd_{}({})".format(val, param))
which would translate to running cd_90(param)
if var
is 90
.示例:
eval("cd_{}({})".format(val, param))
) 如果var
为90
,则转换为运行cd_90(param)
。
func = cd_90 if var else cd_0
then now func
is now a substitute for cd_90
or cd_0
那么现在
func
现在是cd_90
或cd_0
的替代品
I would advise using the 2nd solution as you don't want to call functions using eval
for security concerns.我建议使用第二种解决方案,因为出于安全考虑,您不想使用
eval
调用函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.