-
@ChatGPT cpp 最小费用最大流算法
-
以下代码怎么优化?
def doit(self): fileName='last_pid' ofile = open(fileName, "r") last_pid = ofile.read() _last_pid = self.get_unread(last_pid=int(last_pid)) print ("最新PID: ", _last_pid) if _last_pid > int(last_pid): with open(fileName,'w',encoding='utf-8') as file: file.write(str(_last_pid)) time.sleep(5) self.doit()
-
可以优化为:
def doit(self): fileName='last_pid' with open(fileName, "r") as ofile: last_pid = int(ofile.read()) _last_pid = self.get_unread(last_pid=last_pid) print ("最新PID: ", _last_pid) if _last_pid > last_pid: with open(fileName,'w',encoding='utf-8') as file: file.write(str(_last_pid)) time.sleep(5) self.doit()
优化内容:
- 使用with语句,可以自动关闭文件,不用每次手动关闭文件。
- 将ofile.read()从字符串转换为整型,减少后面的数据类型转换。