简体   繁体   English

基于变量调用两个不同函数之一

[英]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_0cd_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.您可以尝试多种方法,我将列出一些在我脑海中的方法并选择适合您的方法。

  1. Using python's eval function.使用 python 的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)) ) 如果var90 ,则转换为运行cd_90(param)

  1. Using pointers to functions with an if statement.使用带有 if 语句的函数指针。

func = cd_90 if var else cd_0

then now func is now a substitute for cd_90 or cd_0那么现在func现在是cd_90cd_0的替代品

I would advise using the 2nd solution as you don't want to call functions using eval for security concerns.我建议使用第二种解决方案,因为出于安全考虑,您不想使用eval调用函数。

  1. Assigning the functions to values of a dict object, refer to this answer.将函数分配给dict object 的值,请参阅答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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