八个重构技巧使得Python代码更Pythonic( 二 )


def should_i_wear_this_hat(self, hat):if not isinstance(hat, Hat):return Falsecurrent_fashion = get_fashion()weather_outside = self.look_out_of_window()is_stylish = self.evaluate_style(hat, current_fashion)if weather_outside.is_raining:print("Damn.")return Trueelse:print("Great.")return is_stylish# -> refactordef should_i_wear_this_hat(self, hat):if not isinstance(hat, Hat):return Falseweather_outside = self.look_out_of_window()if weather_outside.is_raining:print("Damn.")return Trueelse:print("Great.")current_fashion = get_fashion()return self.evaluate_style(hat, current_fashion)# is_stylish = self.evaluate_style(hat, current_fashion)# return is_stylish8.简化序列检查这是我经常看到的另一件事 。当你需要检查集合中是否有元素时 , 例如在列表中,你不需要写if len(your_list) > 0. 你可以简单地说if your_list 。这是 pep 8 推荐的方法,也称为真值测试 。这是可能的,因为在 Python 中 , 空序列和集合的计算结果为 False 。所以这可以应用于字符串、元组、列表、字典和集合 。
if len(list_of_hats) > 0:hat_to_wear = choose_hat(list_of_hats)# -> refactorif list_of_hats:hat_to_wear = choose_hat(list_of_hats)



推荐阅读