开发者

passing boolean condition as parameter

I have these

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()

can both def be merged to开发者_JAVA百科gether? The only difference between them is "==" , "!="


Yes, in a very generalized fashion - you just need to wrap your head around the facts that (1) functions are first-class values and (2) operators are just functions with special syntactic treatment. For example:

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

Use like (after importing operator - you can do this with a lambda, but for operators the operator module is the cleaner solution) MsgBox1_YesChosen = make_handler(operator.ne) (that's a horrible name btw).


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)


Pass the comparisson operator as a parameter. You can pass not only an operator, but any other functions - -but both "equal" and "not equal" , as well as all other comparisson or arithmetic operators are already defined as proper functions in the "operator" module - your code could become:

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)


I'm assuming this is some event based code, in which case you can't directly modify the number of parameters the event takes. However, you still have two possibilities:

1) You might be able to inspect the e parameter to find what type of event occured (yes or no button click). Check the documentation for whatever library you're using.

2) You can add the third parameter, then use lambdas to provide the third argument when you bind the events (example code assumes 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))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜