可以将条件提取出来,赋值给一个布尔变量再进行判断。例如:
# 原始代码
if x > 0 and y > 0 and z > 0:
# do something
if x > 0 and y > 0 and z > 0:
# do something else
# 改写后的代码
is_positive = x > 0 and y > 0 and z > 0
if is_positive:
# do something
if is_positive:
# do something else
这样可以减少代码中的重复写法,同时也便于维护和修改。
上一篇:避免重复编写相同内容的循环问题
下一篇:避免重复捕获组成员