将布尔条件作为参数传递

5 投票
4 回答
5386 浏览
提问于 2025-04-16 06:36

我有这些

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 个回答

1

把比较运算符当作参数传递。你不仅可以传递一个运算符,还可以传递其他任何函数。其实“等于”和“不等于”这些比较运算符,以及其他所有的比较或算术运算符,已经在“operator”模块中定义成了合适的函数。所以你的代码可以变成:

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

当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。

4

没错,简单来说,你只需要理解两个关键点:第一,函数是可以像其他值一样使用的;第二,运算符其实就是一些特别处理的函数。举个例子:

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

使用方法是这样的(在导入了 operator 之后 - 你也可以用 lambda,但对于运算符来说,使用 operator 模块会更简洁),比如 MsgBox1_YesChosen = make_handler(operator.ne) (顺便说一句,这个名字真糟糕)。

撰写回答