将布尔条件作为参数传递

时间:2010-11-05 14:19:36

标签: python

我有这些

def MsgBox1_YesChosen(sender,e):
    if e.Key != "A": function0() 
    else: 
        function1()
        function2()
        function3()

def MsgBox1_NoChosen(sender,e):
    if e.Key == "A": function0() 
    else: 
        function1()
        function2()
        function3()

可以将两者合并在一起吗?它们之间唯一的区别是“==”,“!=”

4 个答案:

答案 0 :(得分:4)

是的,以一种非常普遍的方式 - 你只需要围绕以下事实:(1)函数是一等值,(2)运算符只是具有特殊句法处理的函数。例如:

def make_handler(predicate)
    def handler(sender, e):
        if predicate(e.Key, 'A'):
            function0()
        else:
            function1()
            function2()
            function3()
    return handler

使用like(在导入operator之后 - 你可以使用lambda执行此操作,但对于运算符,operator模块是更清洁的解决方案)MsgBox1_YesChosen = make_handler(operator.ne)(这是一个可怕的名称btw)。

答案 1 :(得分:1)

def MsgBox1_WhatIsChosen(sender, e, yesOrNo):
  if (e.Key != 'A') == yesOrNo:
    function0() 
  else:
    function1()
    function2()
    function3()

def MsgBox1_YesChosen(sender,e):
  return MsgBox1_WhatIsChosen(sender, e, True)

def MsgBox1_NoChosen(sender,e):
  return MsgBox1_WhatIsChosen(sender, e, False)

答案 2 :(得分:1)

将comparisson运算符作为参数传递。 您不仅可以传递一个运算符,还可以传递任何其他函数 - 但是“相等”和“不相等”,以及所有其他比较算术运算符都已经被定义为“运算符”模块中的正确函数 - 您的代码可以成为:

import operator

def MsgBox1_Action(sender,e, comparisson):
    if comparisson(e.Key, "A"): function0() 
    else: 
        function1()
        function2()
        function3()
MsgBox1_YesChosen = lambda sender, e: MsgBox1_Action(sender, e, operator.eq)
MsgBox1_NoChosen = lambda sender, e: MsgBox1_Action(sender, e, operator.ne)

答案 3 :(得分:0)

我假设这是一些基于事件的代码,在这种情况下,您无法直接修改事件所需的参数数量。但是,您仍有两种可能性:

1)您可以检查e参数以查找发生的事件类型(是或否按钮单击)。查看您正在使用的库的文档。

2)您可以添加第三个参数,然后在绑定事件时使用lambdas提供第三个参数(示例代码假设为Tkinter):

def MsgBox1_Chosen(sender, e, yes_chosen):  
    if (e.Key != "A") == yes_chosen: function0()   
    else:   
        function1()  
        function2()  
        function3()  

msg_box.bind('<Event-Yes>', lambda s,e: MsgBox1_Chosen(s,e,True))
msg_box.bind('<Event-No>', lambda s,e: MsgBox1_Chosen(s,e,False))
相关问题