优化这段代码 def run(self) -> bool: print('check_os_version') # debug if self._check_os_version(): print('uncompress_rom') # debug if self._uncompress_rom(): print('find_scatter_file') # debug if (scatter_file := self._find_scatter_file()) is not None: subp_run('adb reboot bootloader') print('check download status...') # debug if self._check_download_status(False): print('check download status...') # debug if self._download(scatter_file): print('check boot status...') # debug if self._check_download_status(): return wait_for_device(self.serial) return False
时间: 2023-12-17 07:03:09 浏览: 29
可以尝试使用嵌套的条件语句来简化代码,如下所示:
```python
def run(self) -> bool:
print('check_os_version') # debug
if not self._check_os_version():
return False
print('uncompress_rom') # debug
if not self._uncompress_rom():
return False
print('find_scatter_file') # debug
scatter_file = self._find_scatter_file()
if scatter_file is None:
return False
subp_run('adb reboot bootloader')
print('check download status...') # debug
if not self._check_download_status(False):
return False
print('check download status...') # debug
if not self._download(scatter_file):
return False
print('check boot status...') # debug
if not self._check_download_status():
return False
return wait_for_device(self.serial)
```
这样,我们将所有的判断条件都写在了第一层的 `if` 语句中,如果该条件不满足,直接返回 `False`。这样可以减少代码的缩进层数,让代码更加清晰易读。