Skip to main content
 首页 » 编程设计

Python 如何避免很多 if 语句

2025年04月02日15mq0036

我会尽量简化我的问题。我正在使用 py.test 和 appium 编写测试程序。现在:

在应用程序中我有 4 种媒体格式:视频、音频、图像和文档。 我有一个带有上一个、下一个、播放、停止按钮的控制界面。 每种媒体格式都有一个唯一的 ID,例如

video_playbutton, audio_playbutton, document_playbutton, image_playbutton, video_stopbutton audio_stopbutton ...等等

但是我必须做的操作对所有这些都是一样的,例如按下播放按钮。

当我像这样明确地给他们时,我可以解决每个播放按钮

find_element_by_id("video_playbutton") 

当我想按下其他播放按钮时,我必须每次都重复上面一行。像这样:

find_element_by_id("video_playbutton") 
find_element_by_id("audio_playbutton") 
find_element_by_id("image_playbutton") 
find_element_by_id("document_playbutton") 

因为我是从另一个脚本调用这个函数,所以我必须首先区分我得到的是什么字符串,例如:

def play(mediatype): 
    if mediatype == "video" 
          el = find_element_by_id("video_playbutton") 
          el.click() 
    if mediatype == "audio" 
          el = find_element_by_id("audio_playbutton") 
          el.click() 
    if ..... 

解决这种情况的最佳方法是什么?我想避免数百个 if 语句,因为还有停止、下一个、上一个等按钮。

我宁愿寻找这样的东西

def play(mediatype) 
    find_element_by_id(mediatype.playbutton) 

请您参考如下方法:

您可以在两个字典中分离出选择器和操作,这样扩展性更好。否则映射最终会变得很大。这是示例。

dictMedia = {'video':['video_playbutton', 'video_stopbutton','video_nextbutton'], 'audio':['audio_playbutton', 'audio_stopbutton', 'audio_nextbutton']} 
dictOperations = {'play':0, 'stop':1, 'next':2} 
def get_selector(mediatype, operation): 
    return dictMedia[mediatype][dictOperations[operation]] 
 
print get_selector('video', 'play') 

PS:上述操作不检查 key 未找到错误。 但是,我仍然觉得,如果媒体特定操作增长,那么页面对象模型会更好。