python - 具有多个 bool 条件或多个函数的函数?

标签 python function

我正在尝试为我的项目定义一个“util”模块,其中基本 util 函数是“显示窗口”(在本例中为 opencv 项目):

def display_windows(windows_to_display, with_text=False):
    for window_tag, window in windows_to_display:
        cv2.imshow(window_tag, window)

除了基本的“显示”之外,我还想有多种选择,比如
  • 向窗口添加文本 (cv2.putText()
  • 显示窗口后等待 (cv2.waitKey())
  • 销毁窗口 (cv2.destroyAllWindows())

  • 我想知道如何解决这个问题,一种选择是使用默认值添加多个 bool 值,然后有类似的东西:
    def display_windows(windows_to_display, with_text=False, with_wait=False, destroy_first=False):
        if destroy_first:
            cv2.destroyAllWindows()
        for window_tag, window in windows_to_display:
            if with_text:
                cv2.putText(window, 'text', ...)
            cv2.imshow(window_tag, window)
        if with_wait:
            cv2.waitKey(0)
    

    或者,我可以声明几个函数,使用“基础”“显示窗口”,然后添加说:
    def display_windows_and_wait(self, windows_to_display, with_text=False, destroy_first=False):
        display_windows(windows_to_display, with_text)
        cv2.waitKey(0)
    

    等等

    我对这两种选择都不完全满意。
    使用 bool 方法,我不喜欢拥有:
    display_windows(windows, True, True, True)
    

    散落在各处,因为它的信息量不是很大。

    采用多功能方法,嗯,不确定这是否真的有帮助。

    关于哪种方法提高可读性的任何想法?
    或者更好的是,有没有更好的方法来解决这个问题?

    非常感谢

    最佳答案

  • 而不是打电话
    display_windows(windows, True, True, True)
    

    您仍然可以在参数中使用键:
    display_windows(windows, with_text=True, with_wait=True, destroy_first=True)
    
  • 您可以先定义一些常量,然后再使用它们:
    WITH_TEXT = True         # possibly also NO_TEXT = False, NO_WAIT = False, etc.
    WITH_WAIT = True
    DESTROY_FIRST = True
    
    display_windows(windows, WITH_TEXT, WITH_WAIT, DESTROY_FIRST)
    
  • 您只能使用 1 个带有位的参数作为标志:
    WITH_TEXT = 0b001
    WITH_WAIT = 0b010
    DESTROY_FIRST = 0b100
    

    调用函数的示例:
    display_windows(windows, WITH_TEXT|DESTROY_FIRST)
    

    以及函数定义的更改:
    def display_windows(windows_to_display, flags=0):
        if flags & DESTROY_FIRST:
            cv2.destroyAllWindows()
        # and so on
    

    它的优势——在调用你的函数时:
  • 标志(在第二个参数中)可能是*任意顺序,*
  • 带有 False 的标志值被简单地省略。
  • 关于python - 具有多个 bool 条件或多个函数的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61533577/

    相关文章:

    python - 在python中组合2个列表列表

    python - 矩形中的文本 - Pygame

    python - 将元组的 spark RDD 转换为 numpy 数组

    python - 在 Python 中使用 libexif

    c - 指向函数代码结尾的指针

    删除 R 中 apply 语句和函数后面的逗号

    c++ - 在递归函数中覆盖函数参数?

    python - 如何(或是否有可能)使用列表来提取 Python 中的嵌套字典?

    python - 如何在函数中返回可选参数

    r - 覆盖ggplot2中的多个stat_function调用