refactordef state_attributes(self):"""Retu" />
首页 > 文章列表 > 如何使用八个重构技巧使Python代码更具Python风格?

如何使用八个重构技巧使Python代码更具Python风格?

Python Pythonic 重构
215 2023-04-26

1.合并嵌套的if语句

我们从简单的开始。不要像这样嵌套 if 语句,只需将它们合并为一个即可。

def state_attributes(self):
"""Return the state attributes."""
state_attr = {
ATTR_CODE_FORMAT: self.code_format,
ATTR_CHANGED_BY: self.changed_by,
}
return state_attr

# -> refactor
def state_attributes(self):
"""Return the state attributes."""
return {
ATTR_CODE_FORMAT: self.code_format,
ATTR_CHANGED_BY: self.changed_by,
}

5.用if表达式替换if语句

不用 if else​ 语句来设置变量的值,你可以像这样用 if 表达式在一行中设置它。不过,这种重构技术有点值得商榷。有些人仍然喜欢第一个选项,这很好。

if len(list_of_hats) > 0:
hat_to_wear = choose_hat(list_of_hats)

# -> refactor
if list_of_hats:
hat_to_wear = choose_hat(list_of_hats)