将布尔条件作为参数传递

2024-09-30 14:35:28 发布

您现在位置: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()

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


Tags: keyifdefelsesender区别function1function2
3条回答
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)

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

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)

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

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

使用like(在导入^{}-你可以用lambda来完成,但是对于操作符,operator模块是更干净的解决方案)MsgBox1_YesChosen = make_handler(operator.ne)(这是一个可怕的名称btw)。在

相关问题 更多 >