【问题标题】:creating function object with conditional statement before calling在调用之前使用条件语句创建函数对象
【发布时间】:2019-05-03 05:50:54
【问题描述】:

我定义了两个函数(fun1 和 fun2),它们返回一些值,我在 fun3 中调用其中一个函数。我可以在 for 循环中执行 if 条件,但有没有一种方法可以在之前选择该函数。如此处所示。还是有其他方法?

def fun1(a1,b1)
def fun2(a1,b1)

def fun3(a1,b1,some_para):

    if some_para:
        sel_func = fun1()
    else:
        sel_func = fun2()

    for Loop:
        sel_func(a1,b1)

【问题讨论】:

    标签: python python-3.x function


    【解决方案1】:

    函数是对象。只需分配函数而不是调用它。使用您的示例:

    def fun3(a1, b1, some_para):
    
        sel_func = fun1 if some_para else fun2
    
        for Loop:
            sel_func(a1, b1)
    

    【讨论】:

    • 它将永远使用 fun1 永远不会使用 fun2。
    【解决方案2】:
    def fun1(a1,b1)
    def fun2(a1,b1)
    
    
    def fun3(a1,b1,some_para = None):
        sel_func = fun1  if some_para else fun2
        for Loop:
            sel_func(a1,b1)
    

    在函数声明中使用some_para =None,当你调用这个函数时,你总是需要将参数传递给它,如果你不传递任何值,每次只会运行fun1,就会发生属性错误。如果none 使用并且没有传递值fun2 将执行否则fun1 将执行。

    【讨论】:

      【解决方案3】:

      您可以将函数作为参数传递给外部,以便于阅读:

      def fun3(a1, b1, sel_func):
          for Loop:
              sel_func(a1, b1)
      
      # call fun3 with whatever funtion you need in each momment
      fun3(a, b, fun1) 
      fun3(a, b, fun2)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-03-09
        • 1970-01-01
        • 2022-11-10
        • 2013-06-15
        • 2022-12-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多