我正在尝试为我的项目定义一个“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)
除了基本的“显示”之外,我还想有多种选择,比如
等
我想知道如何解决这个问题,一种选择是使用默认值添加多个 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)
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/