1. 异常字句过于宽泛:可以将异常处理语句中的 Exception 改为具体的异常类型,以便更准确地捕获和处理异常。

例如,将以下代码中的 Exception 改为 WebDriverException:

try: self.browser = webdriver.Chrome(options=options) except Exception as e: pass

改为:

from selenium.common.exceptions import WebDriverException

try: self.browser = webdriver.Chrome(options=options) except WebDriverException as e: pass

  1. 重复的代码段:可以将重复的代码段提取出来,封装成一个函数或方法,以便在需要的地方进行调用,避免代码重复。

例如,以下两个方法中的部分代码是重复的:

def start_score_100(self): if not self.running: return

if self.score_thread and self.score_thread.is_alive():
    return

self.start_score_button.config(state='disabled')
self.start_score_button_2.config(state='disabled')
self.stop_score_button.config(state='normal')
self.update_running_label('百分制打分中...')
self.score_thread = Thread(target=self.score_program_100)
self.score_thread.start()

def start_score(self): if not self.running: return

if self.score_thread and self.score_thread.is_alive():
    return

self.start_score_button.config(state='disabled')
self.start_score_button_2.config(state='disabled')
self.stop_score_button.config(state='normal')
self.update_running_label('小分值打分中...')
self.score_thread = Thread(target=self.score_program)
self.score_thread.start()

可以将它们中的重复部分提取出来,封装成一个方法:

def disable_score_buttons(self): self.start_score_button.config(state='disabled') self.start_score_button_2.config(state='disabled') self.stop_score_button.config(state='normal')

然后在 start_score_100 和 start_score 方法中调用该方法:

def start_score_100(self): if not self.running: return

if self.score_thread and self.score_thread.is_alive():
    return

self.disable_score_buttons()
self.update_running_label('百分制打分中...')
self.score_thread = Thread(target=self.score_program_100)
self.score_thread.start()

def start_score(self): if not self.running: return

if self.score_thread and self.score_thread.is_alive():
    return

self.disable_score_buttons()
self.update_running_label('小分值打分中...')
self.score_thread = Thread(target=self.score_program)
self.score

原文地址: https://www.cveoy.top/t/topic/f2iV 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录